public class Student {
private Student() {
}
private String name;
private void eat(String food) {
System.out.println("吃" + food);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String name) {
super();
this.name = name;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
调用
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Class<Student> class1 = Student.class;
Constructor c = class1.getDeclaredConstructor();
c.setAccessible(true);
Student student = (Student) c.newInstance();
// java.lang.reflect.Field m = class1.getDeclaredField("name");
// m.setAccessible(true);
// m.set(student, "张三 ");
Method method = class1.getDeclaredMethod("eat", String.class);
method.setAccessible(true);
method.invoke(student, "苹果");
}
}