[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 184
  • Last Modified:

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?
0
jukkauusi
Asked:
jukkauusi
1 Solution
 
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
 
jukkauusiAuthor Commented:
Thanks.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now