New general object problem

Possible duplicate:
Create an instance of a generic type in Java?

public class MyCache <T extends Taxable> {


    private Map<Long, T> map = new HashMap<Long, T>();

    public void putToMap(Long nip, T t){
        map.put(nip, t);
    }

    public T getFromMap(Long nip){
        return map.get(nip);
    }

}

public class TaxableFactory<T extends Taxable> {

    private MyCache<T> cache;

    public void setCache(MyCache<T> cache) {
        this.cache = cache;
    }

    public TaxableFactory() {

    }

    public void putT(T t) {
        cache.putToMap(t.getNip(), t);
    }

    public  T get(long nip) throws InstantiationException, IllegalAccessException {

        T myT = cache.getFromMap(nip);
        if (myT == null) {

            T newT ;
            putT(newT);

            return null;

        } else
            return myT;

    }

I tried many ways to create a new T in my method get. Looks like I need a little help :) How do I get this to work?

+3
source share
1 answer

Despite using generics, you still need to pass Class as an argument if you want to get a new instance of T.

public  T get(Class<T> clazz, long nip) throws InstantiationException, IllegalAccessException {

    T myT = cache.getFromMap(nip);
    if (myT == null) {

        T newT = clazz.newInstance();
        putT(newT);

        return newT;

    } else
        return myT;

}

Then you call it like this:

.get(SomeTaxable.class, someNip)
+4
source

All Articles