Connecting Tech Pros Worldwide Forums | Help | Site Map

Generics problem accessing static field

Newbie
 
Join Date: Jul 2007
Posts: 15
#1: Jan 14 '09
So here is my problem. I have two beans (one extends the other), and I have one DAO class for each to access their tables (using Hibernate). In most cases the queries will be identical so I also have an abstract DAO class (extended by the other two DAOs) which contains the majority of the queries. I had the methods returning beans of the super class which, if need be, I would cast to the subclass. To avoid this casting I want to switch to generics. I changed over the abstract class with no compiliation erros, but I've hit a bump. In the two beans I have a static String field "entityName" which I access to for the Hibernate calls (Bean.entityName). When I converted to generics the reference changed to T.entityName which now always references the super class. What I need is to access whichever class' entityName I happen to be using.
Example:
Expand|Select|Wrap|Line Numbers
  1. class AbstractBeanDAO <T extends SuperBean> {
  2.  
  3.  public T get(Integer id){
  4.   // this where I have the problem
  5.   Criteria criteria = session.createCriteria(T.entityName);
  6.   // set some criteria
  7.   return criteria.uniqueResult();
  8.  }
  9. }
  10.  
No matter what I set as AbstractBeanDAO <type> it always references SuperBean.entityName. There are times I need SubBean.entityName so I can access the correct table. How can I do this without having to duplicate code in the two DAO subclasses?

JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: Jan 14 '09

re: Generics problem accessing static field


Build one small non-static method in every class that returns that particular value. If the type of that value differs per class make that method return it as an Object.

kind regards,

Jos
Newbie
 
Join Date: Jul 2007
Posts: 15
#3: Jan 14 '09

re: Generics problem accessing static field


I've been thinking about this, and I've come roughly the same conclusion (not yet implemented). I can't just make a non-static method in my beans because I can't make a static call to it. I need to add an abstract getEntityName to the abstract dao, and implement them in the concrete classes. The concrete classes will always use a same (non-generic) bean type so this shouldn't be an issue. Now in the abstract calls wherever I make the T.entityName call I would replace that with this.getEntityName();
Reply