My purpose is to create a generic factory. The code belowed works, but what annoying me is (1) the warning of unchecked conversion, and (2) I must create and initialize any instance of HashMap. Map<String, Set<Object>> m = new HashMap<String, Set<Object>>();
Maybe it is not a factory since I already create any instance. Are there ways to get around this? Thanks
public class InstanceCreation<T> { public static<T> T create(Class<T> cls) throws Exception{ T instance = cls.newInstance(); return instance; } public static void main(String[] argv){ Map<String, Set<Object>> m = new HashMap<String, Set<Object>>(); try{
I am sorry, Please ignore the my earlier post: Check this:
Hi,
According to me,
Now if compiler allows us following: Map<String, Set<Object>> m = new HashMap<String, Set<Object>>(); ---> m.getClass() ---> HashMap<String, Set<Object>>
but in the method create you are using: Class<T> --> <T> --> <String, Set<Object>>
That is why it is asking you to define m with type parameter... if you change :
public static<T> T create(Class cls) throws Exception{ T instance = cls.newInstance(); return instance; }
The problem is that Class objects don't have any information on generics. Even worse (for some), generics don't exist at runtime at all - it's a compile time mechanism.
So although you pass the class of the map, all it knows is that it is java.util.HashMap - the type it stores is "forgotten" once you have compiled the code.