I am trying to make a code to dynamically load a class and use it to create new instances and to run casts. I can make an instance from the newly loaded class using this method: myClass.newInstance();
. But I cannot use it as a type. For example: myClass myObj = new myClass();
It doesn't work. Is it possible to perform somehow?
This is the code I was trying to make:
URL classUrl;
classUrl = new URL("file:///C:/classes/");
URL[] classUrls = { classUrl };
URLClassLoader ucl = new URLClassLoader(classUrls);
Class c = ucl.loadClass("Operation");
Class MyIn = ucl.loadClass("MyInter");
Object o = c.newInstance(); //IT WORKS
System.out.println(((MyIn) o).sum(2, 4)); //IT DOES NOT WORK. Message: MyIn cannot be resolved to a type
MyIn
in your code is a variable name and you later on try to casto
to the interface typeMyIn
- note the same characters here! Change the name of the variableMyIn
to something more Java typical likemyIn
. You could also try to cast o to an instance ofMyIn
using:MyIn instance = MyIn.getClass().cast(o);
and then use it in your application as any other none dynamically loaded instance ofMyIn