Class from string


I have two (or more) classes FirstClass
and SecondClass and depends on ClassName-String i like to construct class FirstClass or SecondClass something like:

String ClassName = "FirstClass";
ClassName Constructed = new ClassName();
Constructed.MethodInFirstClass();
String ClassName = "SecondClass";
ClassName Constructed = new ClassName();
Constructed.MethodInSecondClass();

I know this does not work but is this idea even possible and how?
jukkauusiAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sgomsCommented:
You can do this using the ReflectionAPI.

String ClassName = "FirstClass";
String ClassName = "SecondClass";

//Load the fst class
Class fstClass=Class.forName("FirstClass");

//create an object of the class
fstClass obj=fstClass.newInstance();

//call a method
obj.methodInfstclass();

//repeat teh procedure for the snd class

//Load the snd class
Class sndClass=Class.forName("SecondClass");

//create an object of the class
sndClass obj2=sndClass.newInstance();

//call a method
obj2.methodInsndclass();

you can even extract teh method info, paramerts to be passed etc..by using the refceltion api.

chk out,
http://java.sun.com/docs/books/tutorial/reflect/index.html

-sgoms
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jukkauusiAuthor Commented:
Thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.