我可以使用Java反射所有構造函數(私有,保護和公共):如何才能獲得java類的受保護和公共構造函數?
public Constructor<?>[] getDeclaredConstructors();
我怎樣才能得到一個Java類的唯一保護和公共的構造函數?
我可以使用Java反射所有構造函數(私有,保護和公共):如何才能獲得java類的受保護和公共構造函數?
public Constructor<?>[] getDeclaredConstructors();
我怎樣才能得到一個Java類的唯一保護和公共的構造函數?
getConstructors()
返回公共構造函數。要獲得受保護的構造函數,必須使用getDeclaredConstructors()
,然後遍歷數組並檢查構造函數是否受保護。
下面是代碼示例:
for (Constructor c : clazz.getDeclaredConstructors()) {
if (Modifier.isProtected(c.getModifiers())) {
// this constructor is protected
}
}
如何檢查構造函數是否受到保護? – 2015-02-23 11:06:30
請參閱我添加到我的答案的代碼示例。] [ – AlexR 2015-02-23 11:46:45
請編輯clazz.getConstructors()到for循環的clazz.getDeclaredConstructors() – 2015-02-23 12:37:36
使用java.lang.reflect.Modifier;
用於檢查改性劑通過返回的數組
Class<?> c = Class.forName("ClassName");
Constructor[] allConstructors = c.getDeclaredConstructors();
for (Constructor m : allConstructors) {
String modifier = Modifier.toString(m.getModifiers());
System.out.println(modifier);
}
迭代並檢查:(即:公共的,受保護的,公開的最終等)改性劑。使用Java 8流將會有一個優雅的解決方案。 – Seelenvirtuose 2015-02-23 10:52:29