代码语言:javascript复制
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
public class Text {
public static void main(String[] a){
try {
Class class1 = Class.forName("DEmo");
Field[] fs = class1.getDeclaredFields();//获取所有属性
for(Field f:fs){
System.out.print(Modifier.toString(f.getModifiers()) " ");//获取成员变量修饰符
System.out.print(f.getType().getSimpleName() " ");//获取属性的类型
System.out.print(f.getName());//获取属性的名字
System.out.println();
}
Constructor constructor = class1.getConstructor();
DEmo dEmo = (DEmo)constructor.newInstance();
Field f = class1.getDeclaredField("val");
f.setAccessible(true);//获取权限
f.set(dEmo, 3.14);//改变值
System.out.println(f.get(dEmo));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}