Java -Reflection

Sat, Nov 16, 2019

Read in 1 minutes

Java Reflection API’s are useful in inspecting the class.

java.lang.reflect package has the API to inspect the elements of the class. Using reflection API , you can get the name, fields , interfaces, packages, etc. ..

Reflections are mainly useful when you are using third-party libraries and at runtime, if you want to get the class name or methods or fields of the class.

import java.lang.reflect.Method;
public class TestReflection {
	public static void main(String args[]) {
		Class Student = Student.class;
		String className=Student.getName();
		System.out.println("className=="+className);
		Method[] methods=Student.getMethods();
		for(Method m :methods)
		{
		System.out.println("method names "+m.getName());
		System.out.println(m.getParameterCount());
		}
	}
}
public class Student {
	String name;
	int id;
	String department;
	public Student(int id, String name, String department) {
		this.id=id;
		this.name=name;
		this.department=department;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getDepartment() {
		return department;
	}
	public void setDepartment(String department) {
		this.department = department;
	}

}