直接上代码:
public interface CrudRepository<T> {
Iterable<T> findAll();
}
public class BaseImpl <T> implements CrudRepository<T> {
@Override
public Iterable<T> findAll() {
Class<T> c = getTClass();
System.out.println(c);
common(c);
return null;
}
/**
* 通用的方法使用泛型的class去干一些事情。
*
* @param c 泛型类
*/
private void common(Class<T> c) {
}
/**
* 获取 T.class
*/
public Class<T> getTClass() {
return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
}
public class PhoneRepository extends BaseImpl<Phone> {
public static class Phone {
private static final long serialVersionUID = 1L;
private String name;
private Long price;
private Long updateDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
public Long getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Long updateDate) {
this.updateDate = updateDate;
}
}
}
public class Test {
public static void main(String[] args) {
PhoneRepository phoneRepository = new PhoneRepository();
Iterable<Phone> phones = phoneRepository.findAll();
}
}
结果:
class cn.zero.reflect.PhoneRepository$Phone
工具类:
public class GenericsUtils {
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.
*
* 如public BookManager extends Manager<Book>
*/
public static Class getSuperClassGenericType(Class clazz) {
return getSuperClassGenericType(clazz, 0);
}
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.
*
* 如public BookManager extends Manager<Book>, 返回Book
*/
public static Class getSuperClassGenericType(Class clazz, int index) throws IndexOutOfBoundsException {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return Object.class;
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
}