0

Instantiate generic class gives compile time error: "cannot be instantiated directly"

    public synchronized <T extends Persistable> T read(Class<T> clazz) {
    T temp;
    try {
        if(cache.containsKey(clazz)){
            return (T)cache.get(clazz);
        }else{
            Properties properties = getProperties();
            temp = internalFileManager.read(clazz,     properties.getProperty(clazz.getSimpleName()));
            if(temp == null){
                temp = new T();///cannot be instantiated directly
            }
            cache.put(clazz,temp);
            return temp;
        }
    } catch (Exception e) {
        Log.e("","",e);
        return null;
    }
    }

This is the problem so nor new T() nor new Class() works, it might just easy solution just need some hint.

Pedro Ziff
  • 97
  • 8

2 Answers2

3

You can't instantiate a generic parameter like that (as you've discovered).

However, you do have a Class instance available, so you could call clazz.newInstance() there instead.

(This assumes that the class in question has a public, no-arg constructor. If that's not the case, you'll need to use reflection to find the Constructor instance you need, and then invoke it with the appropriate arguments.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
0

You can't instantiate a generic. I see that you have the Class object of T so you can do

if(temp == null){
   temp = clazz.newInstance();
}

Sidenote:

If T was unbounded, then you could have instantiated it with new Object()

sanbhat
  • 17,522
  • 6
  • 48
  • 64