您的位置:首页 > 编程语言 > Java开发

java获取泛型类型

2014-07-02 14:48 302 查看
package com.example.test;

import java.lang.reflect.Array;

import java.lang.reflect.ParameterizedType;

import java.lang.reflect.Type;

public class Generic extends Base<String> {

public static void main(String[] args) {

Generic c = new Generic();

System.out.println(c.array);

}

Object array;

public Generic() {

array = Array.newInstance(getGenericType(0), 100);

}

}

class Base<T> {

public Class getGenericType(int index) {

Type genType = getClass().getGenericSuperclass();

if (!(genType instanceof ParameterizedType)) {

return Object.class;

}

Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

if (index >= params.length || index < 0) {

throw new RuntimeException("Index outof bounds");

}

if (!(params[index] instanceof Class)) {

return Object.class;

}

return (Class) params[index];

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: