publicstaticvoidmain(String[] args)throwsClassNotFoundException,NoSuchFieldException,NoSuchMethodException,IllegalAccessException,InvocationTargetException,InstantiationException{//获取Class对象Class<?> c =Class.forName("myReflectDemo.Student");//Student s = new Student();Constructor<?> con = c.getConstructor();Object obj = con.newInstance();System.out.println(obj);System.out.println("----------");Field name = c.getDeclaredField("name");//public void setAccessible(boolean flag)将此反射对象的accessible标志设置为指示的布尔值。 值为true表示反射对象应该在使用Java语言访问控制时抑制检查。// 值为false表示反射对象应该在使用Java语言访问控制时执行检查,并在类描述中指出变体。
name.setAccessible(true);
name.set(obj,"张三丰");System.out.println(obj);System.out.println("----------");Field age = c.getDeclaredField("age");
age.setAccessible(true);
age.set(obj,36);System.out.println(obj);System.out.println("----------");Field field = c.getField("address");
field.set(obj,"西安");System.out.println(obj);}
运行结果:
Student{name =null, age = 0, adress = null}
----------
Student{name =张三丰, age = 0, adress = null}
----------
Student{name =张三丰, age = 36, adress = null}
----------
Student{name =张三丰, age = 36, adress = 西安}
运行结果:
public java.lang.String myReflectDemo.Student.toString()
public void myReflectDemo.Student.method1()
public java.lang.String myReflectDemo.Student.method3(java.lang.String,int)
public void myReflectDemo.Student.method2(java.lang.String)
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
-------------
public java.lang.String myReflectDemo.Student.toString()
private void myReflectDemo.Student.function()
public void myReflectDemo.Student.method1()
public java.lang.String myReflectDemo.Student.method3(java.lang.String,int)
public void myReflectDemo.Student.method2(java.lang.String)
-------------
method1