Pregunta

I am having some issues with Class Loading in Java. Inside my project I am trying to dynamically load a class from anywhere. However, I am currently failing at loading a hard-coded one and am still clueless after 6 hours of googling and stack-overflow checking.

I am suspecting that there is an issue with the package name of the class I am loading. My goal is to load the Class LoadAClass.java in the project/resources/dynamicFolderNonInClassPath/loadThis directory. Since I am setting my URLClassLoader to the folder above, its package has been set to

package loadThis;

public class LoadAClass{
static{
System.out.println("I am loaded");
}

(...)
}

However I keep getting a class not found exception.

File file = new File("C:/Users/Robert/Documents/workspace/project/resources/dynamicFolderNonInClassPath/");
if (!file.exists()) System.out.println("typo!"); //debug print
URL url = file.toURI().toURL();
URLClassLoader loader = new URLClassLoader(new URL[]{url});
String classToBeLoaded = "loadThis.LoadAClass";

Class classy = loader.loadClass(classToBeLoaded);
System.out.println(classy.getCanonicalName()); //debug print

I have tried different combinations, like setting the URLClassLoader to the file directly or giving the full /resources/dynamicFolderNonInClassPath/loadThis as URL but how so far no success.

Someone in christmasy mood and seeing the problem? There seems to be some misunderstanding on my part regarding this functionality and I'd like to see it fixed.

¿Fue útil?

Solución

you are missing a forward slash '/'

File file = new File("C:/Users/Robert/Documents/workspace/project/resources/dynamicFolderNonInClassPath");
if (!file.exists()) System.out.println("typo!"); //debug print
URL url = new URL("C:/Users/Robert/Documents/workspace/project/resources/dynamicFolderNonInClassPath/");
URLClassLoader loader = new URLClassLoader(new URL[]{url});
String classToBeLoaded = "loadThis.LoadAClass";

Class classy = loader.loadClass(classToBeLoaded);
System.out.println(classy.getCanonicalName()); //debug print

See the third line

Otros consejos

A .java file isn't a class file. Have you compiled it? You would need a LoadAClass.class file in a "loadThis" directory with your class loader pointing at the directory that contains "loadThis".

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top