Resolving a class name at runtime

G

Glenn Robinson

Hello,

I have two classes that manipulate data in slightly difference ways which
are both subclasses.

I want to be able to determine which class I instantiate at runtime
depending on a value in a properties files.

Once I've got the class name from my properties file what's the coding
required to call the appropriate class?

Thanks
 
C

Christophe Vanfleteren

Glenn said:
Hello,

I have two classes that manipulate data in slightly difference ways which
are both subclasses.

I want to be able to determine which class I instantiate at runtime
depending on a value in a properties files.

Once I've got the class name from my properties file what's the coding
required to call the appropriate class?

Thanks

You need the factory pattern:

public class MyFooFactory {

static Class cl;

static {
//read propertie file, wich has the name of the required class in it.
String classname = properties.getProperty("classname");
cl = Class.forName(classname);
}

public static Foo getFoo(){
//only works if the class has a default no-arg
//constructor
return cl.newInstance();
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top