Quindi ho un pacchetto con classi che estendono JPanel e voglio aggiungerle come schede dinamicamente. All'inizio ho usato una fabbrica e ho registrato tutte le classi e ha funzionato, ma ora voglio caricare tutte le classi nel pacchetto senza conoscerne i nomi. Ho provato diverse cose tra cui Reflections library (che ho trovato molto confuso) e non ho potuto farli funzionare. Apprezzo qualsiasi aiuto.Come ottenere tutti i nomi delle classi in un pacchetto?
Ecco una delle mie prove:
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);
}
}
}
Cosa non ha funzionato con la riflessione? –