3

Possible Duplicate:
Create instance of 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 new T in my get method. Seems like I need little help :) How to do it to m ake it work?

Community
  • 1
  • 1
dantuch
  • 9,123
  • 6
  • 45
  • 68
  • 1
    indeed seems like a dupe, and @Lukas link gives a solution. a hint for why is it impossible: consider an abstract class which extends Taxable, how would new preform on it? – amit May 20 '11 at 15:26

1 Answers1

4

Even though you are using generics, you still would need to pass the Class as an argument if you want to obtain 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;

}

You would then call it like this:

.get(SomeTaxable.class, someNip)
Marcelo
  • 11,218
  • 1
  • 37
  • 51
  • 3
    note using reflection causes significant performance loss. Factory Pattern (as suggested in @Lukas link) is much more elegant and efficient solution. – amit May 20 '11 at 15:28
  • 1
    @amit: It's not as significant today as it used to be... – Lukas Eder May 20 '11 at 15:30
  • @Lukas: well, haven't benchmarked it for a while, so I guess I won't argue about it. However, factory pattern is still much more elegant and readable in my opinion. – amit May 20 '11 at 15:33
  • @Lukas: it's not safe, though. No guaranty there is a no arg constructor. – Puce May 20 '11 at 15:34
  • @guys: You either know your design, or you don't. – Lukas Eder May 20 '11 at 15:37