First of all, I'm not an expert of generics, but I attempted to create a class to persist any type of object into a specified path using the following approach.
public class PersistentObject<T> { /** * Persisted object class. */ private Class<T> clazz; /** * Persisted object. */ private T object; /** * Path of the file where the object is persisted */ private String path; public PersistentObject(String path, Class<T> clazz) { this.clazz = clazz; this.path = path; load(); //Load from file or instantiate new object } } It works fine, but I'm not able to use T as a class that implement the interface Map<K, V>, mainly because of the clazz constructor parameter. Here is what I'm trying to achieve:
PersistentObject<String> test = new PersistentObject<String>("path", String.class); PersistentObject<HashMap<String, Integer>> test2 = new PersistentObject<HashMap<String, Integer>>("path", HashMap<String, Integer>.class); // Compilation error The problem is how can I pass a Class object that allows the instantiation of a HashMap<K, V>, e.g. HashMap<String, Integer>, if there is one?
I guess there is a design flaw in my implementation, some misunderstanding of generics concepts, or both. Any comments or suggestions are really welcome.
Thanks in advance.
clazz? Maybe you have a XY-Problem. You can useHashMap.classto call your constructor since type erasure does remove generic types at runtime. But I doubt that this solves your problem. This question seems to be related.