1. 程式人生 > >實用的反射類工具原始碼分析---SpringSide的工具類

實用的反射類工具原始碼分析---SpringSide的工具類

SpringSide的工具類。
pk: org.springside.core.utils
[code]public class GenericsUtils[/code]

[code]/**
* 通過反射,獲得定義Class時宣告的父類的範型引數的型別. 如public BookManager extends GenricManager<Book>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
* @return the index generic declaration, or <code>Object.class</code> if cannot be determined
*/
public static Class getSuperClassGenricType(Class clazz, int index) {
//得到clazz的父類
Type genType = clazz.getGenericSuperclass();

//如果沒有實現ParameterizedType 介面,即不支援泛型,所以直接返回Object.class
//**這個介面是jdk1.5以後才出來的。
if (!(genType instanceof ParameterizedType)) {
log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
// 返回表示此型別實際型別引數的 Type 物件的陣列,數組裡放的都是對應型別的Class
//如UserAction extends StrutsSecurityAction<User, UserManager> 就返回User和UserManager型別
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();


if (index >= params.length || index < 0) {
log.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "+ params.length);
return Object.class;
}

if (!(params[index] instanceof Class)) {
log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}[/code]