packagereflection;importjava.lang.reflect.Constructor;importjava.lang.reflect.Field;importjava.lang.reflect.InvocationTargetException;/*** 注解
*
*
* 反射: 优点: 可以帮助在没有类的情况下创建对象和调用属性和方法
* 使用注解
* 缺点: 可以使用私有的属性和方法,破坏了代码块的安全性
*
**/
public classFields {public static voidmain(String[] args) {try{
Class class1= Class.forName("reflection.User");//得到构造方法
try{
Constructor constructor= class1.getConstructor(null);
Object object= constructor.newInstance(null);
Field[] fields=class1.getFields();
Field[] fields2=class1.getDeclaredFields();
Field field= class1.getField("age");//得到指定的属性对象
field.set(object, 5);//给属性赋值
Object object2 = field.get(object);//得到属性值
System.out.println(object2);//调用静态的属性
Field field2 = class1.getDeclaredField("weight");
field2.set(null, 10);
Object object3= field2.get(null);
System.out.println(object3);//私有的属性
Field field3 = class1.getDeclaredField("name");
field3.setAccessible(true);//设置可以访问私有属性的权限
field3.set(object,"小花");
Object object4=field3.get(object);
System.out.println(object4);
}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(NoSuchMethodException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}catch(ClassNotFoundException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}