通过反射,可以获取类的构造方法,属性,函数等信息。
package reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class c = Class.forName("reflect.Students");
//通过反射,获取类的构造方法,getConstructs()获取该类及父类的所有构造方法,而getDeclaredConstructs()方法只是获取该类的构造方法
Constructor[] cons = c.getDeclaredConstructors();
System.out.println("construct function:=============");
for (int i = 0; i < cons.length; i++) {
System.out.println(cons[i]);
}
//获取类的属性字段,注意必须是public的属性才可以,非public的属性字段无法得到
Field[] fields = c.getFields();
System.out.println("fiels are:=============");
for (int i = 0; i < fields.length; i++) {
System.out.println(fields[i]);
}
//获取该类的方法,如果没有declared,则连同父类的方法一起获取
Method[] methods = c.getDeclaredMethods();
System.out.println("all methods:=============");
for (int i = 0; i < methods.length; i++) {
System.out.println(methods[i]);
}
//invoke方法第一个参数是调用该方法的对象,第二个参数是该方法的参数,out方法没有参数,此处为null
methods[0].invoke(c.newInstance(), null);
int modify = c.getModifiers();
System.out.println(modify);
}
}
class Students {
public int id;
public String name;
Students() {
}
Students(int id, String name) {
this.id = id;
this.name = name;
}
void out() {
System.out.println("hi, this is a group a students");
}
}