package practice;
public class Student {
private int age;//年龄
private String name;//姓名
public Student(String name) {
this.name = name;
}
private void printInfo(String address){
System.out.println(name+":"+age+":"+address);
}
}
要求达到上面结果:
public class Test {
public static void main(String[] args) {
//1、获得Student类的Class对象
Class clazz = Student.class;
try {
//得到构造方法
Constructor constructor = clazz.getConstructor(String.class);
//通过构造方法,创建对象,操作私有属性,为name赋值
Object stu = constructor.newInstance("小林");
//得到属性名为age,权限为private的属性
Field field = clazz.getDeclaredField("age");
//将age的权限设为可操作
field.setAccessible(true);
//通过set方法为属性赋值
field.set(stu, 21);
//得到方法名为printInfo,参数类型的Class对象为String的Method对象
Method method = clazz.getDeclaredMethod("printInfo", String.class);
//将方法的权限设为可操作
method.setAccessible(true);
//调用Method对象指代的方法
method.invoke(stu, "中国.河南");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}