Code:
public T get(final K key) {
final Class<T> entityClass = T;
return (T) getHibernateTemplate().get(entityClass, key);
}
yeah T really means nothing. are you at all familiar with what generics really are and the concept of erasure? when you compile this, T and K get text substitued with Object. At runtime all generic information is erased, it's only a compile time facility. If the program compiles it must be safe so they throw out all that stuff. As a result you can't instiantate T or refer to it like that - it is not a Class, just a marker for an unknown (possibly bound) type reference.
if you need to reference the class of T, you have two options: pass it in as a constructor or always subclass this thing like this
option 1:
Code:
class GenericDAOImpl<E extends Entity> implements DAO<E> {
private Class<E> entityClass;
public GenericDAOImpl(Class<E> entityClass) {
this.entityClass = entityClass;
}
public <PK extends Serializable> E get(PK pk) {
@SuppressWarnings("unchecked") // hibernates fault, they are still jdk 1.4
E entity = (E) getHibernateTemplate().get(getEntityClass(), pk);
return entity;
}
option 2, a clever little obscure hack, i'm not even sure why this works:
Code:
class GenericDAOImpl<E extends Entity> implements DAO<E> {
private Class<E> entityClass;
public GenericDAOImpl(Class<E> entityClass) {
this.entityClass = ((ParameterizedType) getClass().getGenericSuperclass())
.getGenericTypeArguments()[0]; // pull it with reflection
}
public <PK extends Serializable> E get(PK pk) {
@SuppressWarnings("unchecked") // hibernates fault, they are still jdk 1.4
E entity = (E) getHibernateTemplate().get(getEntityClass(), pk);
return entity;
}
}
class BookDAOImpl extends GenericDAOImpl<Book> { }
// you can also use anonymous classes but if you try to use it directly it will break
new GenericDAOImpl<Book>() { }
have you seen this article http://www.ibm.com/developerworks/ja...enericdao.html
if you search this & the hibernate forum for generic dao there is TONS of various implementations out there. we have ours very well figured out now it is great. Try to design it so that the client applications have to do minimal typing to talk to the database. also i have found the concept of java's generics absolutely fascinating and have embraced them a good bit. They are quite tricky but once you know what you are doing amazingly powerful. One of these days they will erase the concept of erasure and even more cool stuff will be possible. There's lots of good reading out there. This blog has some good stuff, lots of links to good reading too http://blogs.sun.com/ahe/