jabbaa
asked on
Loading the java class dynamically
Let say I have serveral java class:
Class1, Class2, Class3
Then I have a command line program which allow user to input the paramter
java Program Class1
which will then run the following
new Class1()
if the parameter is Class2
new Class2()
How can I write the code such that I can create the class dynamically?
I don't want using the if else case...like..
if(arg.equals("Class1"))
new Class1();
else if(arg.equals("Class2"))
new Class2();
else if(arg.equals("Class3"))
new Class3();
Thanks
Class1, Class2, Class3
Then I have a command line program which allow user to input the paramter
java Program Class1
which will then run the following
new Class1()
if the parameter is Class2
new Class2()
How can I write the code such that I can create the class dynamically?
I don't want using the if else case...like..
if(arg.equals("Class1"))
new Class1();
else if(arg.equals("Class2"))
new Class2();
else if(arg.equals("Class3"))
new Class3();
Thanks
You can use for example Class.forName( classNameString ).newInstance();
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Just do make sure that you have a default constructer for the Class, default constructur i.e. a no argument constructer, otherwise u'll get an error.
ASKER
But how about if my constructor have parameter?
e.g . new Class1(arg1, arg2)
Thanks
e.g . new Class1(arg1, arg2)
Thanks
It is not possible to call parameterized constructor from Class.forName(). However, you can write a dummy no-arg contructor within the class which would call the parameterized constructor with some default parameters.
or u have to initialise them in your switch statement.
somthing like:-
Object obj = Class.forName(arg).newInst ance();
((CustomObject)obj).initia lise(arg1, arg2);
where CustomObject can be the interface or the class u have created.
somthing like:-
Object obj = Class.forName(arg).newInst
((CustomObject)obj).initia
where CustomObject can be the interface or the class u have created.
You can do it this way:
Class cls = Class.forName(arg);
Object obj = cls.getConstructor(new Class[]{cls}).newInstance( new Object[]{arg1, arg2});
Class cls = Class.forName(arg);
Object obj = cls.getConstructor(new Class[]{cls}).newInstance(
Yeah that can also be one of the better ways to do that :)
Class cls = Class.forName(arg);
Object obj = cls.getConstructor(new Class[]{
// here put the argument classes, not cls
String.class,String.class // if arg1 and arg2 are String
}).newInstance(new Object[]{arg1, arg2});
If you want to call a contructor with int parameters, use Integer
int -> Integer
long -> Long
double -> Double
...
You also might have a look at the commons.beanutils.Construc torUtils class. It abstracts away a lot of the noise:
http://jakarta.apache.org/commons/beanutils/api/index.html
Jim
http://jakarta.apache.org/commons/beanutils/api/index.html
Jim