Java reflection application cases
Scenario: on a shopping website, there are first-level classified entities, second-level classified entities, and commodity entities. operations on the three entities mapped to the database include: delete a record, save a record, search for a record by id, and modify a record. If we do not use reflection, follow the general syntax, we need to add, delete, modify, and query the DAO of the three entities. If we use the reflection mechanism, we only need to define a base class generic DAO to implement all the operations, and then let the other three DAO inherit the BaseDAO, then, through reflection, we can identify the specific entity types during the running process to implement operations.
BaseDao. java
Import java. util. List;
Public interface BaseDao {
Public void save (T t );
Public void update (T t );
Public void delete (T t );
Public T findById (Integer id );
Public T findById (String id );
Public List FindAll ();
}
CategoryDao. java
Public interface CategoryDao extends BaseDao {}
CategorySecondDao. java
Public interface CategorySecondDao extends BaseDao {}
ProductDao. java
Public interface ProductDao extends BaseDao {
List FindHotProduct (); // you can use other methods.
}
BaseDaoImpl. java
Public class BaseDaoImpl Extends HibernateDaoSupport implements BaseDao {
Private Class clazz;
Public BaseDaoImpl (){
// Obtain the Class Object:
Class c = this. getClass ();
System. out. println (c );
Type type = c. getGenericSuperclass ();
ParameterizedType pType = (ParameterizedType) type;
System. out. println (pType );
Type [] types = pType. getActualTypeArguments ();
This. clazz = (Class) types [0]; // obtain the specific type
}
@ Override
Public void delete (T t ){
This. getHibernateTemplate (). delete (t );
}
@ Override
Public List FindAll (){
String hql = from + clazz. getSimpleName ();
Return this. getHibernateTemplate (). find (hql );
}
@ Override
Public T findById (Integer id ){
Return (T) this. getHibernateTemplate (). get (clazz, id );
}
@ Override
Public T findById (String id ){
Return (T) this. getHibernateTemplate (). get (clazz, id );
}
@ Override
Public void save (T t ){
This. getHibernateTemplate (). save (t );
}
@ Override
Public void update (T t ){
This. getHibernateTemplate (). update (t );
}
CategoryDaoImpl. java
Public class CategoryDaoImpl extends BaseDaoImpl Implements CategoryDao {
}
CategorySecondDaoImpl. java
Public class CategorySecondDaoImpl extends BaseDaoImpl Implements CategorySecondDao {}
ProductDaoImpl. java
Public class ProductDaoImpl extends BaseDaoImpl Implements ProductDao {
Public List FindHotProduct (){
DetachedCriteria criteria = DetachedCriteria. forClass (Product. class );
Criteria. add (Restrictions. eq (is_hot, 1 ));
Criteria. addOrder (Order. desc (pdate ));
Return this. getHibernateTemplate (). findByCriteria (criteria, 0, 10 );
}