反射是在只知道类的名字和路径的情况下,通过反射获取类中的属性,构造器,方法,并创建该类的对象,使用其中的方法。
反射可以分为 步:创建字符串(内容为类的路径)———- String s=”com.reflection.Test”
使用Class.forName得到该类的类——— Class c =Class.forName(s);
然后同过Class.get来取得属性,构造器,方法的数组——– Filed / Constructor /Method [] f =c.getFiled(); / c.getConstructor(); / c.getMethod();
通过数组来调用属性,构造器,方法————-
其中属性为:f[X].set();
构造器:f[X].newInstance();
方法为:f[x].invoke();
String s ="reflection.Test";
Class c =Class.forName(s);
Method m[]=c.getDeclaredMethods();
Constructor [] cons =c.getDeclaredConstructors();
Filed [] fil =c.getDeclaredFields();
for(Constructor con:cons){
System.out.println(con);
}
for(Method ma:m){
System.out.println(ma);
}
for(Filed fi:fil){
System.out.println(fi);
}
Test te =(Test) cons [0].newInstance(); //构造对象时需要强转
m[4].invoke(te,20); //调用第五个方法,对象为te,参数为20
fil[0].set(te,"lllll"); //给第一个属性赋值
}
结果输出为:
属性列表
private java.lang.String 反射.Test.name
private int 反射.Test.age
构造器列表
public 反射.Test()
方法列表
public void 反射.Test.add(int)
public java.lang.String 反射.Test.getName()
public void 反射.Test.setName(java.lang.String)
public void 反射.Test.setAge(int)
public int 反射.Test.getAge()
特别要注意,静态的方法和属性可以直接调用,当没有参数列表或对象时用null表示。