例一
package cn.xy.test;
public class GenericDao
{
public <T> void add(T t)
{
}
public <T> T getModelById(int id)
{
return null;
}
}
这个类中泛型方法被常规使用,但两个方法之间的T没有联系和相互约束。
例二
package cn.xy.test;
import java.util.Set;
public class GenericDao2<T>
{
public void add(T t)
{
}
public T getModelById(int id)
{
return null;
}
public Set<T> getModels(String conditions)
{
return null;
}
// 泛型类型不能被静态方法使用
//public static void update(T t){}
// 普通泛型方法的写法允许
public static <T> void update(T t)
{
}
}
GenericDao2<Person> g = new GenericDao2<Person>();
Person p = g.getModelById(1);
泛型应用
本文通过两个示例介绍了Java泛型在类和方法中的使用方式。例一展示了泛型方法的独立使用,例二则演示了泛型类的定义及其实例化过程,并说明了泛型在静态方法中的限制。
1584

被折叠的 条评论
为什么被折叠?



