所以我有一個包含擴展JPanel的類,我想將它們動態添加爲標籤。在開始時我使用了一個工廠,我在其中註冊了所有的類,並且它工作正常,但現在我想在不知道名稱的情況下加載包中的所有類。我已經嘗試了幾件事情,包括Reflections library(我發現它很混亂),我無法讓他們工作。我感謝任何幫助。如何獲取包中的所有類名?
這是我的一種嘗試:
public static void registerTab() {
String pkg = TabA.class.getPackage().getName();
String relPath = pkg.replace('.', '/');
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
if (resource == null) {
throw new RuntimeException("Unexpected problem: No resource for "
+ relPath);
}
File f = new File(resource.getPath());
String[] files = f.list();
for (int i = 0; i < files.length; i++) {
String fileName = files[i];
String className = null;
String fileNm = null;
if (fileName.endsWith(".class")) {
fileNm = fileName.substring(0, fileName.length() - 6);
className = pkg + '.' + fileNm;
}
if (className != null) {
if (!tabClasses.containsKey(className))
tabClasses.put(fileNm, className);
}
}
}
反射出了什麼問題? – 2013-03-20 09:26:52