jeudi 4 août 2016

Load a class that is not in the classpath

I want to load a class (because I want to use it after).

I already tried that:

String dir = "file:/myFolder1/myFolder2/target/classes/";
    try {
      URL url = new URL(dir);
      Object a = new Object();
      URLClassLoader c1 = new URLClassLoader(new URL[] { url }, a.getClass().getClassLoader());
      c1.loadClass("gui.dialog.myProcess");
    }
    catch (MalformedURLException e) {
      e.printStackTrace();
    }
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

But when I run it, I get that output:

Exception in thread "main" java.lang.NoClassDefFoundError: traceability/abstracts/Process
at java.lang.ClassLoader.defineClass1(Native Method)
 [....]
Caused by: java.lang.ClassNotFoundException: traceability.abstracts.Process

My problems are:

  • Why I have an exception ClassNotFoundExeception: traceability.abstracts.Process ? Because I never want to call this one, I want to call gui.dialog.myProcess! EDIT : I found but there's an other problem. Indeed, the traceability.abstracts.Process problem is because: my myProcess class extends that Process class. But how can I do?

  • Can I load a entire folder instead of a class? Because my original problem is: I'm not in a place where I can call the class directly, so I need to load it (because I can't put it in the build path). But I don't know the name of the class.. (I can pass the name in the parameters of my script but it's quite ugly).

I already tried those links: Loading classes not present in the classpath and Reflection getDeclaredMethods() and class that is not in classpath

Thank you, Clément.





Aucun commentaire:

Enregistrer un commentaire