新的通用对象问题

时间:2011-05-20 15:20:05

标签: java generics

  

可能重复:
  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;

    }

我尝试了很多方法在我的get方法中创建新的T.好像我需要一些帮助:)如何做到这一点才能起作用?

1 个答案:

答案 0 :(得分:4)

即使你使用泛型,如果你想获得一个新的T实例,你仍然需要将Class作为参数传递。

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;

}

然后你会这样称呼它:

.get(SomeTaxable.class, someNip)
相关问题