dimanche 7 janvier 2018

How to Load external .class file in Java?

I am trying to load and get some information of class in Java. In the following code [file, file2] are in the same eclipse project and [file3] is in the android studio project. But the following line get java.lang.ClassNotFoundException

Class c3 = loader.loadClass("edu.test.activity.GPSActivity");  

Does java support to load class that does not exist in the current project ? If possible how can I get?

private void test() {
    File file = new File("C:/jworkspace/all_java/bin/edu/test/annotate/");
    File file2 = new File("C:/jworkspace/all_java/bin/edu/test/collections/");
    File file3 = new File("C:/android/workspace/AllTest/app/build/intermediates/classes/debug/edu/test/activity/");
    try {
        URLClassLoader loader = URLClassLoader
                .newInstance(new URL[] { file.toURI().toURL(), file2.toURI().toURL(), file3.toURI().toURL() });
        Class c = loader.loadClass("edu.test.annotate.Account");
        Class c2 = loader.loadClass("edu.test.collections.StackTest");
        Class c3 = loader.loadClass("edu.test.activity.GPSActivity");
        System.out.println(c.getName());
        System.out.println(c2.getName());
        System.out.println(c3.getName());
        loader.close();
    } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
    }
}





Aucun commentaire:

Enregistrer un commentaire