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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With