java反射访问私有类问题
Java code
public class Person {
public String name="aaa";
public Person(){
System.out.println("person");
}
public Person(String name){
System.out.println(name);
}
private Person(List list){
System.out.println("list");
}
}
Java code
public void test3() throws Exception{
Class cla=Class.forName("com.itcast.reflect.Person");
Constructor c = cla.getDeclaredConstructor(List.class);
c.setAccessible(true);
Person p = (Person) c.newInstance(new ArrayList());
System.out.println(p.name);
}
运行后出错如下:
java.lang.NoSuchMethodException: com.itcast.reflect.Person.<init>(java.awt.List)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at com.itcast.reflect.demo2.test3(demo2.java:34)
at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:70)
at org.junit.internal.runners.TestMethod.runTestUnprotected(TestMethod.java:75)
at org.junit.internal.runners.TestMethod$2.run(TestMethod.java:148)
at org.junit.internal.runners.Roadie.runProtected(Roadie.java:81)
at org.junit.internal.runners.TestMethod.runTestProtected(TestMethod.java:146)
at org.junit.internal.runners.TestMethod.run(TestMethod.java:139)
at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMethod(JUnit4ClassRunner.java:88)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
at org.junit.internal.runners.Roadie.runProtected(Roadie.java:81)
at org.junit.internal.runners.TestClass.runProtected(TestClass.java:100)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
请高手指教……
------解决方案--------------------java.awt.List?
------解决方案--------------------private Person(List list)这里的List是java.awt.List,传入的参数是ArrayList,ArrayList并没有继承或实现java.awt.List
------解决方案-------------------- 引入jar 包时引错了, 应该引入 java.util.List,而不是 java.awt.List
------解决方案--------------------刚才运行了下,你用java.util.List,是可以执行的