package demo.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class A{
private int a;
//public protected均可以
//private 修饰时必须在反射中添加setAccessible(true)
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
public class ReflectDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Class clazz=Class.forName("demo.reflection.A");
A a = new A();
a.setA(3);
for(Field f : clazz.getDeclaredFields())
{
f.setAccessible(true);
System.out.println(f.getName()+"==>"+f.isAccessible()+"=="+f.get(a));
}
Method d = clazz.getDeclaredMethod("getA", null);
d.setAccessible(true);
System.out.println(">>>>>>>>>"+d.invoke(a, null));
Method dd = clazz.getDeclaredMethod("setA", new Class[]{int.class});
dd.invoke(a, new Object[]{1});
System.out.println("======>"+a.getA());
for(Method m : clazz.getMethods())
{
System.out.println(m.getName()+"==>"+m.isAccessible());
}
}catch(Exception ex){
System.out.println(ex);
}
}
}