Results 1 to 3 of 3
- 08-14-2011, 02:38 PM #1
Senior Member
- Join Date
- Aug 2009
- Posts
- 294
- Rep Power
- 0
How create new instance of a class given the classname in string form?
Hi!
I got a method that takes a string and should return an instance of the class with the string as name.
For example given the string "TestApp" should execute:
return new TestApp();
Atm I'v solved it as follows:
I knew from the start this was a bad idea, but thought I could figure something out along the way.PHP Code:public class ActivityManager { public static Activity newAction(String mode, Person p){ if (mode.equals("RunAwayFrom")){ return new RunAwayFrom(p); } if (mode.equals("Babble")){ return new Babble(p); } if (mode.equals("Walking")){ return new Walking(p); } if (mode.equals("Dance")){ return new Dance(p); } if (mode.equals("Panic")){ return new Panic(p); } if (mode.equals("MakePhoneCall")){ return new MakePhoneCall(p); } ....
I didn't so thats why im here :P
The classes are not always in same package either. Moste of them are but some are in a secondary subpackage.
Do you have any idea on how to solve this?
- 08-14-2011, 02:53 PM #2
Member
- Join Date
- Aug 2011
- Posts
- 95
- Rep Power
- 0
You need to learn about Java Reflection. Java Reflection is the right way to solve a problem like this.
See this tutorial, for example:
Trail: The Reflection API (The Java™ Tutorials)
And once you get used to the inherent complexity of Reflection, you'll realize that it is a pretty good solution to a number of problems. (So don't be so hard on yourself. ;-)
- 08-15-2011, 08:05 AM #3
Senior Member
- Join Date
- Aug 2009
- Posts
- 294
- Rep Power
- 0
Awsome!
For those who ask the same question, heres how it should look:
PHP Code:public static Activity getActivity(String mode){ String[] sources = {"activity.actions.","activity.actions.cop."}; for(String s : sources){ try{ Class c = Class.forName(s+mode); Constructor con = c.getConstructors()[0]; return (Activity) con.newInstance(p); } catch (Exception e){ //e.printStackTrace(); } } return null; }
Similar Threads
-
what is <classname>.class
By brendonwoodford in forum New To JavaReplies: 1Last Post: 08-30-2010, 01:51 PM -
create new instance of variable class
By Fedor in forum New To JavaReplies: 5Last Post: 04-12-2009, 08:13 PM -
create Instance of class in Javascript
By TDMaster in forum JavaServer Pages (JSP) and JSTLReplies: 1Last Post: 03-09-2009, 04:26 PM -
How to create object dynamically with class name known in string format
By ranu_gokhe in forum Advanced JavaReplies: 1Last Post: 04-09-2008, 02:15 AM -
<variable>(Java.lang.string) in <classname> cannot be applies to ()
By inksmithy in forum New To JavaReplies: 5Last Post: 01-13-2008, 10:36 PM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks