获取构造器信息
package d18_3_1; import java.lang.reflect.Constructor; import java.util.Arrays; /** * 获取构造器的四个方法 * * 运行结果如下 * [private d18_3_1.Test2(), public d18_3_1.Test2(java.lang.String,int,java.lang.String), public d18_3_1.Test2(java.lang.String,int), protected d18_3_1.Test2(java.lang.String)] * protected d18_3_1.Test2(java.lang.String) * [public d18_3_1.Test2(java.lang.String,int,java.lang.String), public d18_3_1.Test2(java.lang.String,int)] * public d18_3_1.Test2(java.lang.String,int) */ public class ClassInfo1 { public static void main(String[] args) throws NoSuchMethodException, SecurityException { // 获取构造器的四个方法 Class c = Test2.class; // 1 获取所有的构造器,不论是否私有 Constructor[] dcs1 = c.getDeclaredConstructors(); System.out.println(Arrays.toString(dcs1)); // 2获取在所有构造器中,指定的构造器 Constructor dc1=c.getDeclaredConstructor(String.class); System.out.println(dc1); // 3 获取所有public构造器 Constructor[] dcs2 = c.getConstructors(); System.out.println(Arrays.toString(dcs2)); // 4在所有public构造器中,获取指定的构造器 Constructor dc2=c.getConstructor(String.class,int.class); System.out.println(dc2); } } class Test2 { private String name; private int age; String sex; private Test2() { } protected Test2(String name) { super(); this.name = name; } public Test2(String name, int age) { super(); this.name = name; this.age = age; } public Test2(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Test [name=" + name + ", age=" + age + "]"; } }
时间: 2024-09-29 04:34:17