Invoke Methods in Java Reflection


Create entities package and create new class named Student as below:

package entities;

public class Student {

	private String id;
	private String name;
	private int age;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String say() {
		return "Hello World";
	}

	public String hi(String message) {
		return "Hello " + message;
	}

	public double avg(double math, double physical, double chemistry) {
		return (math * 3 + physical * 2 + chemistry) / 6;
	}

}




package reflection;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import entities.Student;

public class Main {

	private static void InvokeSayMethod(Student student) {
		try {
			Class studentClass = student.getClass();
			Method sayMethod = studentClass.getMethod("say", new Class[] {});
			String result = sayMethod.invoke(student, new Object[] {}).toString();
			System.out.println(result);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	private static void InvokeHiMethod(Student student) {
		try {
			Class studentClass = student.getClass();
			Method hiMethod = studentClass.getMethod("hi", new Class[] { String.class });
			String result = hiMethod.invoke(student, new Object[] { "Kevin" }).toString();
			System.out.println(result);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	private static void InvokeAvgMethod(Student student) {
		try {
			Class studentClass = student.getClass();
			Method avgMethod = studentClass.getMethod("avg", new Class[] { double.class, double.class, double.class });
			double result = (double) avgMethod.invoke(student, new Object[] { 7, 6, 10 });
			System.out.println("Avg: " + result);
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		}
	}

	public static void main(String[] args) {

		Student student = new Student();
		InvokeSayMethod(student);
		InvokeHiMethod(student);
		InvokeAvgMethod(student);

	}

}




Hello World
Hello Kevin
Avg: 7.166666666666667