I'm trying to use custom Class as a value in a Map<String, Class<?>>
. Following are relevant parts of code:
Following is declaration and initialization of Map in main()
:
public static Map<String, Class<?>> mapQuery2ResponseType = new HashMap<String, Class<?>>();
static {
mapQuery2ResponseType.put("string1", CustomClass1.class);
mapQuery2ResponseType.put("string2", CustomClass2.class);
mapQuery2ResponseType.put("string3", CustomClass3.class);
}
Now I'm using this map to typecast an object to one of these classes: (assume that all classes contain a method getName()
which return a String
)
String name = (
(
mapQuery2ResponseType.get("string1")
)obj1
).getName();
where, obj1
is of generic type T
,
but it's not allowing me to do so and says: Syntax error on token "obj1", delete this token
.
Please help me to understand where am I doing wrong?
Edit:
When I use following code, it worked perfectly giving me the expected result,
String name = (
(
CustomClass1
)obj1
).getName();
and obj1
is of the same type as returned by mapQuery2ResponseType.put("string1", CustomClass1.class);
.
Here I can see 1 thing... if I use use it directly, i use it as "CustomClass1"
, whereas if I get it from map by mapQuery2ResponseType.get("string1")
, it returns "CustomClass1.class"
. I'm not sure if there is any difference in these two approaches? If there is, what is it?
So actually there wont be any conversion, it's just that I'm using it for large number of classes, and so trying to use a generalized approach.
Edit2:
as given in this question: Java: difference between “CustomClass1” and “CustomClass1.class”?, I think, reflection is the only solution for this task. But can anybody explain how to do it using reflection?