本帖最后由 高正新 于 2014-3-16 10:55 编辑
Person类如下:
- package com.fly.reflect;
- import java.util.List;
- public class Person {
- public Person() {
- System.out.println("person");
- }
-
- public Person(String name) {
- System.out.println("name:" + name);
- }
-
- public Person(String name, int age) {
- System.out.println("person name:" + name + " age:" + age);
- }
-
- private Person(List list) {
- System.out.println("list");
- }
-
- public void testMe() {
- System.out.println("可以了");
- }
- }
复制代码 反射得到构造函数方法如下:
- //反射构造函数:public Person(List list)
- @Test
- public void test4() throws Exception {
- Class clazz = Class.forName("com.fly.reflect.Person");
- Constructor c = clazz.getConstructor(List.class); //原来是这里写错了。
- c.setAccessible(true); //暴力反射
- Person p = (Person)c.newInstance(new ArrayList());
- p.testMe();
- }
复制代码
我运行为什么总是报错啊?
- Exception in thread "main" java.lang.NoSuchMethodException: com.fly.reflect.Person.<init>(java.util.List)
- at java.lang.Class.getConstructor0(Class.java:2810)
- at java.lang.Class.getConstructor(Class.java:1718)
- at com.fly.reflect.Demo2.main(Demo2.java:11)
复制代码
|