A brief discussion on the methods of defining generic classes and defining generic methods in java

  • 2020-06-15 08:32:43
  • OfStack

1. Generics in methods


public static <T> T backSerializable(Class<T> clazz , String path ,String fileName){
 
 FileInputStream fis = null;
 ObjectInputStream ois = null;
 Object obj = null;
 
 try {
  
  fis = new FileInputStream(path + fileName);
  ois = new ObjectInputStream(fis);
  obj = ois.readObject();
  
 } catch (FileNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (ClassNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }finally{
  
  try {
  if( fis!=null) fis.close();
  if( ois!=null) ois.close();
  } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  
  
 }
 
 
 
 return (T)obj;
 }

2. Define generic classes


public class PageHibernateCallback<T> implements HibernateCallback<List<T>>{
 
 private String hql;
 private Object[] params;
 private int startIndex;
 private int pageSize;
 

 public PageHibernateCallback(String hql, Object[] params,
  int startIndex, int pageSize) {
 super();
 this.hql = hql;
 this.params = params;
 this.startIndex = startIndex;
 this.pageSize = pageSize;
 }



 public List<T> doInHibernate(Session session) throws HibernateException,
  SQLException {
 //1  perform hql statements 
 Query query = session.createQuery(hql);
 //2  The actual parameter 
 if(params != null){
  for(int i = 0 ; i < params.length ; i ++){
  query.setParameter(i, params[i]);
  }
 }
 //3  paging 
 query.setFirstResult(startIndex);
 query.setMaxResults(pageSize);
 
 return query.list();
 }

}



Related articles: