目的
- 测试目的:
- 测试如何将一个只知道类名里面的所有属性变量 所有方法 所有构造器访问出来
- 提示:利用新型for循环
需要访问的Property类
package myreflect.reflect1;
public class Property {
public int propertyNum;
private String propertyName = "马云的财产" ;
private String property = "norach";
private final static int CONSUMMER=0;
public Property() {
}
public Property(int propertyNum, String propertyName, String property) {
this.propertyNum = propertyNum;
this.propertyName = propertyName;
this.property = property;
}
@Override
public String toString() {
return "Property{" +
"propertyNum=" + propertyNum +
", propertyName='" + propertyName + '\'' +
", property='" + property + '\'' +
'}';
}
public int p0(int a){
System.out.println("这是Property中的有参数有返回值的私有方法p1");
return 0;
}
private void p1(){
System.out.println("这是Property中的无参数无返回私有方法p1");
}
private int p2(int a){
System.out.println("这是Property中的有参数有返回值的私有方法p2");
return a;
}
public static void p3(){
System.out.println("这是Property中的无参数无返回值静态方法p3");
}
}
Driver01测试文件
package myreflect.reflect1;
import org.junit.Test;
import java.lang.reflect.Field;
public class Driver01 {
@Test
public void getAttribute() throws IllegalAccessException, InstantiationException {
Class cla = new Property().getClass();
Property property = (Property) cla.newInstance();
Field[] fields = cla.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
Object o = fields[i].get(property);
System.out.println(fields[i].getName()+"的值是"+o);
}
}
}
测试结果
