# Java 构造函数反射 ## Java反射 - Java构造函数反射 以下四种方法来自\` Class \`类获取有关构造函数的信息: \`\`\` Constructor\[\] getConstructors() Constructor\[\] getDeclaredConstructors() Constructor getConstructor(Class... parameterTypes) Constructor getDeclaredConstructor(Class... parameterTypes) \`\`\` \`getConstructors()\`方法返回当前和超类的所有公共构造函数。 \`getDeclaredConstructors()\`方法返回当前类的所有声明的构造函数。 getConstructor(Class ... parameterTypes)和getDeclaredConstructor(Class ... parameterTypes)通过参数类型获取构造函数对象。 ![image-20241112102636561](https://hgh-typora-image.oss-cn-guangzhou.aliyuncs.com/img/image-20241112102636561.png) ## 例子 以下代码显示了如何对构造函数执行反射。 \`\`\` import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.util.ArrayList; class MyClass { public MyClass(int i, int j, String s) { } public MyClass(T t) { } public int getInt(String a) { return 0; } } public class Main { public static void main(String\[\] args) { Class c = MyClass.class; System.out.println("Constructors for " + c.getName()); Constructor\[\] constructors = c.getConstructors(); ArrayList constructDescList = getConstructorsDesciption(constructors); for (String desc : constructDescList) { System.out.println(desc); } } public static ArrayList getConstructorsDesciption( Constructor\[\] constructors) { ArrayList constructorList = new ArrayList\<\>(); for (Constructor constructor : constructors) { String modifiers = getModifiers(constructor); String constructorName = constructor.getName(); constructorList.add(modifiers + " " + constructorName + "(" + getParameters(constructor) + ") " + getExceptionList(constructor)); } return constructorList; } public static ArrayList getParameters(Executable exec) { Parameter\[\] parms = exec.getParameters(); ArrayList parmList = new ArrayList\<\>(); for (int i = 0; i \< parms.length; i++) { int mod = parms\[i\].getModifiers() \& Modifier.parameterModifiers(); String modifiers = Modifier.toString(mod); String parmType = parms\[i\].getType().getSimpleName(); String parmName = parms\[i\].getName(); String temp = modifiers + " " + parmType + " " + parmName; if (temp.trim().length() == 0) { continue; } parmList.add(temp.trim()); } return parmList; } public static ArrayList getExceptionList(Executable exec) { ArrayList exceptionList = new ArrayList\<\>(); for (Class c : exec.getExceptionTypes()) { exceptionList.add(c.getSimpleName()); } return exceptionList; } public static String getModifiers(Executable exec) { int mod = exec.getModifiers(); if (exec instanceof Method) { mod = mod \& Modifier.methodModifiers(); } else if (exec instanceof Constructor) { mod = mod \& Modifier.constructorModifiers(); } return Modifier.toString(mod); } } \`\`\` 上面的代码生成以下结果。 !\[img\](https://atts.w3cschool.cn/attachments/jimg/java_reflection/EXAMPLE__56417AAB5F59C43C78A2.png)