I'm a beginner at java Reflection/Dynamic Loading. I want to load a specific Class ( that implements an Interface ) from a jar-File. Further more i want to initialize an Object of this Class and cast it to my specific Interface.
I tried .loadClass()
, class.forName()
and if I cast Myclass.newInstance
to my Interface I'll get a ClassCastException.
How could I program my plugin-Loader, so it loads my class in my jar and cast it to myInterface
?
Edit
My Server has the same Interface as my Plugins implement. Now I want my Plugins "loaded" and cast to my Interface so I could use them normally.
Edit
Here is some sample Code of my try to get a rid of these errors :D
URL url = f.toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class<ModInterface> c = (Class<ModInterface>)cl.loadClass("com.myapp.mod");
Class<? extends ModInterface> sub = c.asSubclass(ModInterface.class);
Constructor<? extends ModInterface> con = sub.getConstructor();
ModInterface mi = con.newInstance();
another code sample what I've done:
ClassLoader loader = PluginLoader.class.getClassLoader();
URL url = new URL("jar:file:" + f.getAbsolutePath() + "!/");
URLClassLoader ucl = new URLClassLoader(new URL[] { url }, loader);
Class iInterfaceClass = Class.forName("com.myapp.mod", true, ucl);
ModInterface mi = (ModInterface) iInterfaceClass.newInstance();
Error:
java.lang.ClassCastException: com.myapp.mod cannot be cast to myapp.ModInterface
After some help provided by you i've done the following:
URL url = f.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader loader = ModInterface.class.getClassLoader();
ClassLoader cl = new URLClassLoader(urls, loader);
Class<?> loadedClass = Class.forName("com.myapp.mod", true, cl);
Class<? extends ModInterface> pluginClass = loadedClass.asSubclass(ModInterface.class);
ModInterface mi = pluginClass.newInstance();
Now i get this error -> java.lang.ClassCastException: class com.myapp.mod thrown at loadedClass.asSubclass(..); The specific class is found, because if i change com.myapp.mod to whatever it throws a classnotfound execption. I've tried to use the ModInterface ClassLoader, but nothin changed. with(out) i'll get the same error.
Note:// I use 2 Projects. 1 for my Server App, the other for my Plugin that should be loaded. Both have the same Interface.
edit://
with this code i get an Object of type Object from my desired class, but it's not an instance of my ModInterface although my Class implements my ModInterface. If i try to cast my Object to my ModInterface a Error appears. Here is my short code:
Class c = clazzLoader.loadClass(element.getName().replaceAll(".class", "").replaceAll("/", "."));
Object instance = c.newInstance();