一:
package com.test.fanxing;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test{
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Class<Student> cl = Student.class;//获取class对象
// Class cl=Class.forName("com.test.fanxing.Student");
Student st = (Student) cl.newInstance();//获得类的实例
Field filed = cl.getDeclaredField("name");//获取Student类中的指定属性的Field对象(每个属性对应一个对象,这里对应的是name属性)
System.out.println("filed===="+filed);
filed.setAccessible(true);//取消属性的访问权限控制,即private声明的属性也可以进行访问
System.out.println("init Name====="+filed.get(st));//获取Student类中属性name的初始化的值
filed.set(st, "tyandhy");//给Student类中的name属性进行重新赋值
System.out.println("new Name====="+filed.get(st));//获取重新赋值后的属性值
st.getMyName();//调用Student类中的共用方法
Field filed1 = cl.getDeclaredField("age");获取Student类中的指定属性的Field对象(每个属性对应一个对象,这里对应的是age属性)
filed1.setAccessible(true);
System.out.println("init age===="+filed1.getInt(st));
Method method = cl.getDeclaredMethod("getName",String.class,int.class);//调用对象的getName方法,并声明传递参数类型
method.setAccessible(true);//取消私有方法的访问权限控制
method.invoke(st, "java",26);//给调用的私有方法传递参数
}
}
二:
package com.test.fanxing;
public class Student {
public Student(){}
private String name="rte";
private int age=5;
public String addr="sjg";
public void getMyName(){
System.out.println("ty1");
}
private void getName(String name,int age){
System.out.println("===="+name+"===="+age);
}
}