Get all public constructors of the class through the class.getConstructors() method.
If the class has no public constructor, or the class is an array class, or the class reflects a primitive type or void, then an array of length 0 is returned.
1 import lombok.Data; 2 3 /** 4 * Created by hunt on 2017/6/27. 5 * 测试的实体类 6 * @Data 编译后会自动生成set、get、无惨构造、equals、canEqual、hashCode、toString方法 7 */ 8 @Data 9 public class Person {10 private String name;11 private int age;12 public Person(){}13 public Person(String name){...}14 protected Person(int age){...}15 private Person(String name,int age){...}16 17 }
1 /** 2 * Created by hunt on 2017/6/27. 3 */ 4 public class NewInstanceTest { 5 public static void main(String[] args) { 6 Class<Person> personClass = Person.class;//获取Class实例 7 Constructor<?> constructor[] = personClass.getConstructors(); 8 for (Constructor<?> con : constructor) { 9 System.out.println(con);10 }11 12 }13 }
1 import lombok.Data; 2 3 /** 4 * Created by hunt on 2017/6/27. 5 * 测试的实体类 6 * @Data 编译后会自动生成set、get、无惨构造、equals、canEqual、hashCode、toString方法 7 */ 8 @Data 9 public class Person {10 private String name;11 private int age;12 private Person(String name){...}13 protected Person(int age){...}14 private Person(String name,int age){...}15 16 }
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;//获取Class实例 9 Constructor<?> constructor[] = personClass.getConstructors();10 System.out.println(constructor.length);11 for (Constructor<?> con : constructor) {12 System.out.println(con);13 }14 15 }16 }
Get all the constructors of the class (public, protected, default, and private constructors) through the class.getDeclaredConstructors() method.
If the class has a default constructor, it is included in the returned array. If this Class object represents an interface, a primitive type, an array class, or void, this method returns an array of length 0.
1 /** 2 * Created by hunt on 2017/6/27. 3 */ 4 public class NewInstanceTest { 5 public static void main(String[] args) { 6 Class<Person> personClass = Person.class;//获取Class实例 7 Constructor<?> constructor[] = personClass.getDeclaredConstructors(); 8 System.out.println(constructor.length); 9 for (Constructor<?> con : constructor) {10 System.out.println(con);11 }12 13 }14 }
Note: The elements in the returned method array are not sorted, nor in any specific order.
The above is the detailed content of Get a tutorial on constructor examples in classes. For more information, please follow other related articles on the PHP Chinese website!