- public class Test{
-
- public static void main(String[] args) throws Exception {
-
- Class cls = Person.class;//获取Person类的字节码
-
- Constructor constructor1 = cls.getConstructor();//调用getConstructor()获取Person无参构造方法
- Person p1 = (Person) constructor1.newInstance();//通过调用newInstance()来执行无参构造方法
-
- Constructor constructor2 = cls.getConstructor(int.class);//调用getConstructor(*.class)获取Person带参构造方法
- Person p2 = (Person) constructor2.newInstance(1);//通过调用newInstance(int)来执行带参构造方法
- }
- }
- class Person{
- public Person(){System.out.println("无参构造方法");}
- public Person(int i){System.out.println("带参构造方法");}
- }
复制代码
|
|