第21天dao模型二(更为精简)之泛型的反射

来源:互联网 发布:移除数组中的重复元素 编辑:程序博客网 时间:2024/06/10 00:43


1、使用带有泛型信息的类:
  a、两边都带有泛型的,一定要一致
   ArrayList<String> list = new ArrayList<String>();
  b、单边有泛型信息也是可以的
   ArrayList<String> list = new ArrayList ();  新程序员调用老程序员的内容
   ArrayList list = new ArrayList<String>();   老程序员调用新程序员的内容
 2、自定义泛型:
  a、可以在定义类的后面就声明泛型,类中的实例方法就可以直接使用。
   public class Demo1<T> {//类级别的泛型定义。类中的“实例方法”就可以直接使用
 
    //<T>:泛型定义的声明。在返回值的前面
    public  T findOne(Class<T> clazz){
     return null;
    }
  b、静态方法必须单独定义后才能使用。在返回值得前面定义
    public static <T> void u1(T t){
    
    }
  c、可以同时生命多个泛型的定义
   public static <K,V> V findValue(K k){//MAP
    return null;
   }
  
 3、使用带有泛型信息的类注意事项:
  只有对象类型才能作为泛型方法的实际参数


dao接口不变。

主要是实现变了,不需要写那么多代码,在basedao中做了处理即对泛型进行了反射

import java.io.Serializable;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import org.hibernate.Session;import com.itheima.dao.CustomerDao;import com.itheima.dao.Dao;import com.itheima.domain.Customer;//借助Hibernatepublic class BaseDao<T> implements Dao<T> {private Session session = null;//当做有了这个对象private Class clazz;//从哪个表中操作public BaseDao(){//泛型的反射:目的,给成员变量clazz赋值,好让查询、删除知道从哪个表中操作System.out.println(this.getClass().getName());//this:就是哪个实实在在的对象  CustomerDao cDao = new CustomerDaoImpl();  CustoemrDaoImpl的实例Type type = this.getClass().getGenericSuperclass();//获取带有泛型信息的父类   "BaseDao<Customer>"     Type是Class类的接口ParameterizedType pType = (ParameterizedType)type; clazz = (Class) pType.getActualTypeArguments()[0];}public void add(T t) {session.save(t);}public void update(T t) {session.update(t);}public void delete(Serializable id) {T t  =findOne(id);session.delete(t);}public T findOne(Serializable id) {System.out.println(clazz.getName());return (T) session.get(clazz, id);}}
package com.jxnu.dao.impl;import java.util.List;import com.itheima.dao.CustomerDao;import com.itheima.domain.Customer;public class CustomerDaoImpl extends BaseDao<Customer> implements CustomerDao {//public CustomerDaoImpl(){//super();//}public List<Customer> findRecords(int startIndex, int pageSize) {// TODO Auto-generated method stubreturn null;}}


package com.jxnu.dao.impl;import java.util.List;import com.itheima.dao.UserDao;import com.itheima.domain.User;public class UserDaoImpl extends BaseDao<User> implements UserDao {@Overridepublic List<User> findAll() {// TODO Auto-generated method stubreturn null;}}

实现层减少了代码。


关键代码是:

private Class clazz;//从哪个表中操作
 public BaseDao(){
  //泛型的反射:目的,给成员变量clazz赋值,好让查询、删除知道从哪个表中操作
  System.out.println(this.getClass().getName());
  //this:就是哪个实实在在的对象  CustomerDao cDao = new CustomerDaoImpl();  CustoemrDaoImpl的实例
  Type type = this.getClass().getGenericSuperclass();//获取带有泛型信息的父类   "BaseDao<Customer>"     Type是Class类的接口
  ParameterizedType pType = (ParameterizedType)type;
  clazz = (Class) pType.getActualTypeArguments()[0];
 }
 




1 0
原创粉丝点击