I can get all constructors(private, protected and public) using Java Reflection:
public Constructor<?>[] getDeclaredConstructors();
How can I get only protected and public constructors of a java class ?
getConstructors()
returns public constructors. To get protected constructors you have to use getDeclaredConstructors()
and then iterate over the array and check whether constructor is protected.
Here is the code sample:
for (Constructor c : clazz.getDeclaredConstructors()) {
if (Modifier.isProtected(c.getModifiers())) {
// this constructor is protected
}
}
use java.lang.reflect.Modifier;
for checking the modifiers(ie: public, protected, public final, etc ):
Class<?> c = Class.forName("ClassName");
Constructor[] allConstructors = c.getDeclaredConstructors();
for (Constructor m : allConstructors) {
String modifier = Modifier.toString(m.getModifiers());
System.out.println(modifier);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.