1、使用带有泛型信息的类:
a、两边都带有泛型的,一定要一致
arraylist list = new arraylist();
b、单边有泛型信息也是可以的
arraylist list = new arraylist (); 新程序员调用老程序员的内容
arraylist list = new arraylist(); 老程序员调用新程序员的内容
2、自定义泛型:
a、可以在定义类的后面就声明泛型,类中的实例方法就可以直接使用。
public class demo1 {//类级别的泛型定义。类中的“实例方法”就可以直接使用
//:泛型定义的声明。在返回值的前面
public t findone(class clazz){
return null;
}
b、静态方法必须单独定义后才能使用。在返回值得前面定义
public static void u1(t t){
}
c、可以同时生命多个泛型的定义
public static 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 implements dao { 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 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 implements customerdao { // public customerdaoimpl(){// super();// } public list findrecords(int startindex, int pagesize) { // todo auto-generated method stub return 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 implements userdao { @override public list findall() { // todo auto-generated method stub return 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 type是class类的接口
parameterizedtype ptype = (parameterizedtype)type;
clazz = (class) ptype.getactualtypearguments()[0];
}
