package com.javase.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; /** * 反射类中的构造方法 */ public class ReflectConstructorText01 { public static void main(String[] args) { //创建一个字符串拼接对象 StringBuilder s = new StringBuilder(); try { //获取类 Class vipClass = Class.forName("com.javase.bean.Vip"); //public class Vip { s.append(Modifier.toString(vipClass.getModifiers()));//拼接类的修饰符 s.append(" class "); s.append(vipClass.getSimpleName());//拼接类名 s.append("{\n");//拼接类体开始符 Constructor[] constructors = vipClass.getConstructors();//获取类中的所有构造方法 //遍历 for (Constructor constructor : constructors){ //public Vip(int no, String name, String birth) { s.append("\t");//拼接制表符 s.append(Modifier.toString(constructor.getModifiers()));//拼接构造方法修饰符 s.append(" ");//空格 s.append(vipClass.getSimpleName());//拼接构造方法名(构造方法名与类名一样) s.append("("); //拼接参数 //获取参数 Class[] parameterTypes = constructor.getParameterTypes(); //遍历 for (Class parameterType : parameterTypes){ s.append(parameterType.getSimpleName()); s.append(","); } if (parameterTypes.length > 0){//当参数类型数组中有元素的时候删除最后一个字符“,” s.deleteCharAt(s.length() - 1); } s.append("){}\n"); } s.append("}");//拼接类体结束符 System.out.println(s); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
package com.javase.bean; public class Vip { int no; String name; String birth; boolean sex; public Vip() { } public Vip(int no) { this.no = no; } public Vip(int no, String name) { this.no = no; this.name = name; } public Vip(int no, String name, String birth) { this.no = no; this.name = name; this.birth = birth; } public Vip(int no, String name, String birth, boolean sex) { this.no = no; this.name = name; this.birth = birth; this.sex = sex; } @Override public String toString() { return "Vip{" + "no=" + no + ", name='" + name + '\'' + ", birth='" + birth + '\'' + ", sex=" + sex + '}'; } }
/* 程序运行结果: public class Vip{ public Vip(int,String,String,boolean){} public Vip(int,String,String){} public Vip(int,String){} public Vip(int){} public Vip(){} } */