package com;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestBean {
private int age;
public static void main(String []args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchFieldException{
try {
Class<?> class1=Class.forName("com.TestBean");
Object tObject=class1.newInstance();
Field field=class1.getDeclaredField("age");
field.setAccessible(true); //设置私有属性范围
field.set(tObject, 10);
System.out.print(field.get(tObject));
try {
Method method=class1.getMethod("setAge", int.class);
method.invoke(tObject, 11);
Method getMethod=class1.getMethod("getAge");
System.out.println(getMethod.invoke(tObject));
} catch (NoSuchMethodException 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 (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
java反射设置私有属性和获取属性
最新推荐文章于 2023-12-19 14:06:24 发布