Is there a more object oriented method for selecting a class based on a string than using if-else statements (or switch)?
I have a system where I receive a string from an outside library, and need to select a specific class based on that string. Unfortunately, I have no control over the string I receive. Is there a more object-oriented way to do this in Java than
if(string.equals(CASE1)){
return new CaseOneObject();
} else if (string.equals(CASE2)){
return new CaseTwoObject();
}开发者_Python百科 else if
...
Each string corresponds to a single class, but there isn't a reliable way to derive the class name from the string.
Or put the names or classes in a map and select them using the string as the key.
Map<String, Class<?>> classes = new HashMap<String, Class<?>>;
Class<?> aClass = com.github.my.overlong.package.SomeClass.class;
classes.put("silly_string_a", aClass);
/* .... */
You could setup a static mapping like this at the top of your class managing this:
static Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
static {
classMap.put("case1", CaseOneObject.class);
classMap.put("case2", CaseTwoObject.class);
}
And then lookup the string you get from the outside library to create an instance if it's available:
Class<?> clazz = classMap.get(string);
if (clazz != null) {
return clazz.newInstance();
}
you may want to store a map of your instances and use it when the string has sent
Map<String,Object> map = new HashMap<String,Object>();
map.put("SomeString",new MyObject());
map.put("SomeString2",new MyObject2());
or you can save the class instead of new MyObject2() and create new instance.
now when you want to get the data you go:
return map.get(myString);
As others have noted, there is the Map<String, Object>
solution, which is quite nice; however if you really want to switch off of Strings, you cannot do it until Java 7 becomes available.
Project coin added several extensions to the Java language. One of those extensions was "switch statements based on Strings", an example of the supported String enabled switch statement follows.
SIMPLE EXAMPLE: Show the simplest possible program utilizing the new feature.
String s = ...
switch(s) {
case "foo":
processFoo(s);
break;
}
ADVANCED EXAMPLE: Show advanced usage(s) of the feature.
String s = ...
switch(s) {
case "quux":
processQuux(s);
// fall-through
case "foo":
case "bar":
processFooOrBar(s);
break;
case "baz":
processBaz(s);
// fall-through
default:
processDefault(s);
break;
}
Store the String to classname mapping in a map. Use reflection with proper exception handling to instantiate the class
Edit
map.put ("case1", "class1")
....
Class.forName(map.get("case1")).newInstance();
However, you will need to Type the returned object to desired one before being able to do something useful with it.
精彩评论