簡介
spring 源碼是個大寶庫,我們能遇到的大部分工具在源碼里都能找到,所以筆者開源的 mica 完全基于 spring 進行基礎增強,不重復造輪子。今天我要分享的是在 spring 中優雅的獲取泛型。
獲取泛型
自己解析
我們之前的處理方式,代碼來源 vjtools(江南白衣)。
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
34
35
36
|
/** * 通過反射, 獲得class定義中聲明的父類的泛型參數的類型. * * 注意泛型必須定義在父類處. 這是唯一可以通過反射從泛型獲得class實例的地方. * * 如無法找到, 返回object.class. * * 如public userdao extends hibernatedao<user,long> * * @param clazz clazz the class to introspect * @param index the index of the generic declaration, start from 0. * @return the index generic declaration, or object.class if cannot be determined */ public static class getclassgenerictype( final class clazz, final int index) { type gentype = clazz.getgenericsuperclass(); if (!(gentype instanceof parameterizedtype)) { logger.warn(clazz.getsimplename() + "'s superclass not parameterizedtype" ); return object. class ; } type[] params = ((parameterizedtype) gentype).getactualtypearguments(); if ((index >= params.length) || (index < 0 )) { logger.warn( "index: " + index + ", size of " + clazz.getsimplename() + "'s parameterized type: " + params.length); return object. class ; } if (!(params[index] instanceof class )) { logger.warn(clazz.getsimplename() + " not set the actual class on superclass generic parameter" ); return object. class ; } return ( class ) params[index]; } |
resolvabletype 工具
從 spring 4.0 開始 spring 中添加了 resolvabletype 工具,這個類可以更加方便的用來回去泛型信息。
首先我們來看看官方示例:
1
2
3
4
5
6
7
8
9
10
11
|
private hashmap<integer, list<string>> mymap; public void example() { resolvabletype t = resolvabletype.forfield(getclass().getdeclaredfield( "mymap" )); t.getsupertype(); // abstractmap<integer, list<string>> t.asmap(); // map<integer, list<string>> t.getgeneric( 0 ).resolve(); // integer t.getgeneric( 1 ).resolve(); // list t.getgeneric( 1 ); // list<string> t.resolvegeneric( 1 , 0 ); // string } |
詳細說明
構造獲取 field 的泛型信息
1
|
resolvabletype.forfield(field) |
構造獲取 method 的泛型信息
1
|
resolvabletype.formethodparameter(method, int ) |
構造獲取方法返回參數的泛型信息
1
|
resolvabletype.formethodreturntype(method) |
構造獲取構造參數的泛型信息
1
|
resolvabletype.forconstructorparameter(constructor, int ) |
構造獲取類的泛型信息
1
|
resolvabletype.forclass( class ) |
構造獲取類型的泛型信息
1
|
resolvabletype.fortype(type) |
構造獲取實例的泛型信息
1
|
resolvabletype.forinstance(object) |
更多使用 api 請查看,resolvabletype java doc: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/resolvabletype.html
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000018669505