//学生类
public class Student {
private String name;
private int age;
public String address;
public Student() {
}
private Student(String name){
}
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
}//测试类Class<?> c = Class.forName("FanShe.Student");
Student s=new Student("张三",15,"成都");//普通创建
Constructor<?> con = c.getConstructor(String.class, int.class, String.class);//反射创建
Object obj = con.newInstance("张三", 15, "成都");//set方法赋值s.setName("张三");//普通赋值
Field name = c.getDeclaredField("name");
name.setAccessible(true);
name.set(obj,"张三");//调用方法s.Study();
Method study = c.getMethod("Study");
study.invoke(obj);//反射可访问用私有方法及成员变量private void method(){
System.out.println("method");
}//学生类中私有方法Method method = c.getDeclaredMethod("method");
method.setAccessible(true);
method.invoke(obj);//测试类调用
|
|