Perhaps I'm going about this all wrong. I have been banging my head against this problem for several days now (nearing a week). Perhaps there is a better way and I am just not seeing it.
Let me explain in full what it is I'm trying to do.
In short is modular class loading at runtime. I write Foo.class and Bar.class Foo extends Bar. I am trying to write a program that knows what the definition of Foo is and goes to to a directory (entered at runtime) that loads all .class files there (assuming) that they are subtypes of Bar. Generate a new instance of each of these classes and cast them to Foo and use them within the program.
These are the 5 classes i am using
public class Main {
public static void main (String args[]){
Why w = new Why();
}
}
public class Foo extends Bar{
public Foo(){
super();
}
@Override
public void hitMe(Why w) {
w.out("FROM FOO");
}
}
public class Bar {
public Bar(){
}
public void hitMe(Why w){
w.out("FROM BAR");
}
}
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
public class TestProject {
public static boolean execute(Why w){
try {
ArrayList<Class> classList = new ArrayList<Class>();
ArrayList<String> classes = new ArrayList<String>();
File dir = new File("C:\\Users\\Akira\\Desktop\\Target");
ClassLoader cl = new URLClassLoader(new URL[]{dir.toURI().toURL()});
try {
classList.add(cl.loadClass("Foo"));
System.err.println(classList.size());
Bar r = (Bar) classList.get(0).newInstance();
r.hitMe(w);
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(classList.toString());
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
return false;
}
}
public class Why {
/**
* @param args the command line arguments
*/
public Why(){
boolean execute = TestProject.execute(this);
System.out.println(execute);
}
public void out(String string) {
System.err.println(string);
}
}
Once the code is compiled into .class files i cut the Foo.class and paste it into the target directory. I then get
java.lang.ClassDefNotFoundException: Bar
at java.net.URLClassLoader$1.run(URLClassLoader.java: 202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.j ava:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:3 06)
at java.lang.ClassLoader.loadClass(ClassLoader.java:2 47)
at TestProject.execute(TestProject.java:25)
at Why.<init>(Why.java:16)
at Main.main(Main.java:12)
{EDIT}: If i move Bar.class to the same target folder as Foo.class, it will not throw the ClassDeffNotFoundException, however it throws a ClassCastExcception when attempting to cast Foo to Bar.