首页 > 代码库 > 通过构造函数实例化对象

通过构造函数实例化对象

 1 /**
 2  * Created by hunt on 2017/6/27.
 3  * 测试的实体类
 4  * @Data 编译后会自动生成set、get、无惨构造、equals、canEqual、hashCode、toString方法
 5  */
 6 @Data
 7 public class Person {
 8     private String name;
 9     private int age;
10     public Person(String name){
11         this.name = name;
12     }
13     public Person(int age){
14         this.age = age;
15     }
16     public Person(String name,int age){...}
17 
18 }
 1 import java.lang.reflect.Constructor;
 2 
 3 /**
 4  * Created by hunt on 2017/6/27.
 5  */
 6 public class NewInstanceTest {
 7     public static void main(String[] args) {
 8         Class<Person> personClass = Person.class;
 9         try {
10             Constructor<?> constructor  = personClass.getConstructor(java.lang.String.class);
11             Person p = (Person) constructor.newInstance("hunt");
12             System.out.println(p);
13         } catch (Exception e) {
14             e.printStackTrace();
15         }
16     }
17 }

技术分享

总结:通过class.getConstructor(parameterTypes)获得对应的构造器,然后通过constructor.newInstance(parameterTypes)实例化对象。

通过构造函数实例化对象