Java获取泛型T的类型 T.class

直接上代码:

1
2
3
4
5
public interface CrudRepository<T> {

Iterable<T> findAll();

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
public class Test {

public static void main(String[] args) {
PhoneRepository phoneRepository = new PhoneRepository();
Iterable<Phone> phones = phoneRepository.findAll();
}
}

结果:
class cn.zero.reflect.PhoneRepository$Phone



工具类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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];
}
}