Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to run a class who’s name is unknown in advance?

 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The name of the class is assigned to a variable classNmae at runtime. How to run this class? Assume the class is started by run() method.
1) Can I use:
className aObj = new className();
aObj.run();
2) Can I use
String cmd = "java " + className;
Runtime rt = Runtime.getRuntime();
pr = rt.exec(cmd);
Thanks
[ March 21, 2002: Message edited by: Bruce Jin ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64858
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a job for (fanfare) Java Reflection!
Check out the Class.forName() method, and the Class.newInstance() method.
hth,
bear
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks bear.
I looked into Class.forName(). Seems I need to make all classes extend an interface or superclass to make this dynamic invoke work.
But I don’t see why I need reflection.
 
Steve Deadsea
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do it with reflection even if you don't want to extend another class or implement an interface. With reflection you could query the class to see what methods it has and choose one of them to run. Or you could see it it has a main method and run that.
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How this can be done (using reflection)?
Foe example, I use reflection and find out there is a main method in my class Example, how do I invoke it after loading the Class?
Class c = Class.forName("Example");
Thanks
[ March 22, 2002: Message edited by: Bruce Jin ]
 
David Duran
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've never used reflection so I'm not too sure on the syntax for the usage of these methods but you might want to look at:
getMethod(...) in class Class & invoke(...) in class Method
[ March 22, 2002: Message edited by: David Duran ]
 
Adam Blinkinsop
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David's right. Here's some example code:

So yeah. A little reflection (great stuff), and lots of try-catch blocks. All of which is in the JavaDocs! (*tear*)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic