dimanche 24 avril 2016

How to get the package name of an external .class (Java Reflection)

Here is my folder : /Users/huyvo/Desktop/demo It contains .class

How do I get the package name of an external .class?

public static Set<Class<?>> loadPackageFromPath(String path){
Set<Class<?>> thePackage = new HashSet<>();

FilenameFilter classFilter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".class");
    }
};

File f = new File(path);


if(f.isDirectory())

for (File file : f.listFiles(classFilter)){ 

    String packageName =  // Package name??


    String className =  packageName + "." + file.getName().substring(0, file.getName().lastIndexOf('.'));


    try { 
        thePackage.add(Class.forName(className));

    } catch (ClassNotFoundException e) { e.printStackTrace(); }  
}   

return thePackage;

}





Aucun commentaire:

Enregistrer un commentaire