我怎样才能只获得 java class 的受保护构造函数和 public 构造函数?

How can I get only protected and public constructors of a java class?

我可以使用 Java 反射获取所有构造函数(私有、受保护和 public):

public Constructor<?>[] getDeclaredConstructors();

我怎样才能只获得 java class 的受保护和 public 构造函数?

getConstructors() returns public 构造函数。要获得受保护的构造函数,您必须使用 getDeclaredConstructors() 然后遍历数组并检查构造函数是否受保护。

这是代码示例:

for (Constructor c : clazz.getDeclaredConstructors()) {
    if (Modifier.isProtected(c.getModifiers())) {
       // this constructor is protected
    }
}

使用 java.lang.reflect.Modifier; 检查修饰符(即:public、protected、public final 等):

    Class<?> c = Class.forName("ClassName");
    Constructor[] allConstructors = c.getDeclaredConstructors();
    for (Constructor m : allConstructors) {
        String modifier = Modifier.toString(m.getModifiers());
        System.out.println(modifier);
     }