楼主你这一行代码 public int getAge{ 怎么可以编译通过呢?少了括号啊!,应该是public int getAge(){ 这样吧!
下面饿已经为你把反射私有构造方法跟反射普通方法都写好了,楼主看下是否正确、、、
package com.yting.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class Person {
public String name;
private int age;
private Person(String name, int age) {
this.name = name;
this.age = age;
}
private Person(String name) {
this.name = name;
}
private Person() {
}
public int getAge() {
return age;
}
public static void main(String[] args) throws Exception {
Person p = new Person("zhangsan", 12);
Method method_common = p.getClass().getMethod("getAge"); //反射私有方法public int getAge();
System.out.println(method_common.invoke(p)); //输出结果
//反射私有构造方法
Constructor method_constructor = p.getClass().getDeclaredConstructor(String.class,int.class);
method_constructor.setAccessible(true);
Person p_test = (Person) method_constructor.newInstance("lisi",56);
System.out.println("p_test --> age :" + p_test.getAge());
}
} |