How to dynamically create instance of .class
Hi sir...
I am working(more properly studying) on the server side of a distributed system.
The server receives correctly a .class file and write it correctly to a file.
At this point the server should create a new instance of the class : so I redefinied the default classloader ("AgentClassLoader") that correctly creates the class,still not instaciated.
Now I "think" I should use reflection to start theclass....but I don't know how....I'm not very fond reflection!!
Note that this class is a thread with only the run and has a constructor...so it should be very simple...How do I (what is the simplest way to) instanciate the class....? I do I create the constructor? How do I call the start or run method of my thread? (should I call run() or start())?
Thank you so much.
andy
[832 byte] By [
madcowzza] at [2007-11-26 19:44:18]

Ok , So 've tried in many ways (forname,getinstance...) but I can't create an instance and run this very simple thread class...
Now I'll post my code...
Server class : //is very simple...
AgentClassLoader loader = new AgentClassLoader();//creates instance of my redefinied classloader
//Load the main class through agentclassloader
Class class=loader.loadClass(AGENT_NAME,FILE_PATH,false);
//I won't post my classloader code because it works correctly
System.out.println("Now Launching Agent..");
try {
class = Class.forName("app.MyTestAgent", true,loader);//I tryied these methods..for name and new instance....but without success
//Note : "app" is the package and MyTestAgent is the class I want to instanciate
class.newInstance();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
2nd Class : "MyTestAgent" extend Thread and is veeery simple!!
public class MyTestAgent extends Thread {
Platform platform;//this is a simple collector class with only simple data inside
public MyTestAgent (Platform platform) {
this.platform = platform;
}
public void run(){//I have to run this method!!
//I won't post this code because is very simple
(retrieves parameters from plaform object)
}
Anybody knows how to do it?
Please Help Me!!
Thanks a lot guys ... bye..
class = Class.forName("app.MyTestAgent", true,loader);
class.newInstance();
I'm surprised if that compiles.
Try this instead: Class clazz = Class.forName("app.MyTestAgent", true,loader);
MyTestAgent agent = (MyTestAgent) clazz.newInstance();