想通过反射获取类的构造函数,可是………那么问题来了
- import java.lang.reflect.Constructor;
- class ReflectDemo
- {
- public static void main(String[] args) throws ClassNotFoundException,NoSuchMethodException
- {
- Person p = new Person();
- //获取Class对象的三种方式
- Class clazz1 = Person.class;
- Class clazz2 = p.getClass();
- Class clazz3 = Class.forName("Person");
- System.out.println("clazz1="+clazz1.toString());
- System.out.println("clazz2="+clazz2);
- System.out.println("clazz3="+clazz3);
-
- //获取所有构造方法的两种方式
- Constructor con1 = clazz1.getConstructor();
- System.out.println("con1 = "+con1);
- Constructor con2 = clazz1.getConstructor(String.class,int.class);
- System.out.println("con2 = "+con2);
- System.out.println("Hello World!");
- }
- }
- class Person
- {
- String name;
- private int age;
- Person(){}
- Person(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public void setName(String name)
- {
- this.name = name;
- }
- private int getAge()
- {
- return age;
- }
- private void setAge(int age)
- {
- this.age = age;
- }
- }
复制代码
编译通过,运行报错:
D:\CODE\heima\reflect>javac ReflectDemo.java
注: ReflectDemo.java使用了未经检查或不安全的操作。
注: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。
D:\CODE\heima\reflect>java ReflectDemo
clazz1=class Person
clazz2=class Person
clazz3=class Person
Exception in thread "main" java.lang.NoSuchMethodException: Person.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at ReflectDemo.main(ReflectDemo.java:18)
这是为什么?哪里错了?
|
|