2

If I need to return a Class instanced based on a String (e.g., creating logic from JSON), how should that be written?

My initial thought was a switch, but in the Android framework's version of Java, it looks like switch statements don't allow Strings.

Next thought was a HashMap:

private HashMap<String, Class> classMap = new HashMap<String, Class>();
classMap.put("someClass", SomeClass.class)?
// ... etc
String someString = jsonObject.getString("someProperty");
Class classRef = classMap.get(someString);
SomeSuperClass classInstance = new classRef();

This doesn't work. I'd rather not if/else down a lengthy list of possibilities.

Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
momo
  • 3,885
  • 4
  • 33
  • 54
  • 1
    No version of Java allows switch statements with strings (except Java 7, but everyone knows that's just a myth to keep us quiet). – Tharwen May 07 '12 at 18:41

3 Answers3

6

Just use Class<?> clazz = Class.forName("com.yourpackage.YourClass") Then to instantiate it: clazz.newInstance();

Thomas Dignan
  • 7,052
  • 3
  • 40
  • 48
1

You can also load the class with having the constructors parameters.

E.g.

public static void load(String p)
    throws ClassNotFoundException, InstantiationException,
    IllegalAccessException{
        Class cl = classLoader.loadClass(p);
        Constructor c = cl.getConstructor(String.class);
        Plugin plug = (Plugin) c.newInstance("myArgument");
    }
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
  • Shouldn't you return the created Plugin instance? – Natix May 07 '12 at 18:56
  • We can return the created `Plugin` instance but my intention was to display example that you can create instance of the Object though it has constructor with arguments. – Bhavik Ambani May 07 '12 at 19:00
0

Your approach using a map is what I would do (and you'll see it in Factory Pattern implementations). You're just not instantiating the class correctly:

Class classRef = classMap.get(someString);
SomeSuperClass classInstance = classRef.newInstance();
Brian Roach
  • 76,169
  • 12
  • 136
  • 161