Java Example with ClassLoader

I have a little problem. I am learning Java SE and find the ClassLoader class. I am trying to use it in the below code: I am trying to use a URLClassLoader to dynamically load a class at runtime.

URLClassLoader urlcl = new URLClassLoader(new URL[] {new URL("file:///I:/Studia/PW/Sem6/_repozytorium/workspace/Test/testJavaLoader.jar")});
Class<?> classS = urlcl.loadClass("michal.collection.Stack");
for(Method field: classS.getMethods()) {
     System.out.println(field.getName());
}
Object object = classS.newInstance();
michal.collection.Stack new_name = (michal.collection.Stack) object;

The Java virtual machine does not see me in the class, and I get the following exception:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: michal cannot be resolved to a type michal cannot be resolved to a type at Main.main(Main.java:62)

Do you know how I can solve this problem?

+5
source share
3 answers
Class<?> classS = urlcl.loadClass("michal.collection.Stack");
[...]
Object object = classS.newInstance();
michal.collection.Stack new_name = (michal.collection.Stack) object;

So, you are trying to dynamically load the class, and then statically refer to it. If you can already statically refer to it, then it loads, and you cannot load it again. You will need to access the methods by reflection.

, , , . ( , ), .

public interface Stack {
   [...]
}
[...]
    URLClassLoader urlcl = URLClassLoader.newInstance(new URL[] {
       new URL(
           "file:///I:/Studia/PW/Sem6/_repozytorium/workspace/Test/testJavaLoader.jar"
       )
    });
    Class<?> clazz = urlcl.loadClass("michal.collection.StackImpl");
    Class<? extends Stack> stackClass = clazz.asSubclass(Stack.class);
    Constructor<? extends Stack> ctor = stackClass.getConstructor();
    Stack stack = ctor.newInstance();

( .)

. URLClassLoader.newInstance URLClassLoader. Class.newInstance .

+4

, . newInstance() Class, loadClass().

0

, . Stack, . urlclassloader . , , . , , . , cclass . , , , sstack, rsukt NoClassDefErrors .. , classcastexception.

0

All Articles