利用java反射获取泛型类的类型参数具体类对象

代码有这样的需求, 要求在运行时利用java反射机制获取泛型类的参数类对象, 

例如

class Family

{

List<Person> members;

}

希望用反射得到类似Person.class的类对象. 

如果是非泛型的字段, 例如 Person father; 则用Field.getType()方法即可: 

    /**
     * Returns a {@code Class} object that identifies the
     * declared type for the field represented by this
     * {@code Field} object.
     *
     * @return a {@code Class} object identifying the declared
     * type of the field represented by this object
     */
    public Class<?> getType() {
        return type;
    }

但对于上述这种泛型的字段,  则通过getType似乎无法得到所要的结果, 我一开始总想着用getType的结果转换,  结果是行不通的.  最后发现必须使用另一个方法才可以:

    /**
     * Returns a {@code Type} object that represents the declared type for
     * the field represented by this {@code Field} object.
     *
     * <p>If the {@code Type} is a parameterized type, the
     * {@code Type} object returned must accurately reflect the
     * actual type parameters used in the source code.
     *
     * <p>If the type of the underlying field is a type variable or a
     * parameterized type, it is created. Otherwise, it is resolved.
     *
     * @return a {@code Type} object that represents the declared type for
     *     the field represented by this {@code Field} object
     * @throws GenericSignatureFormatError if the generic field
     *     signature does not conform to the format specified in
     *     <cite>The Java&trade; Virtual Machine Specification</cite>
     * @throws TypeNotPresentException if the generic type
     *     signature of the underlying field refers to a non-existent
     *     type declaration
     * @throws MalformedParameterizedTypeException if the generic
     *     signature of the underlying field refers to a parameterized type
     *     that cannot be instantiated for any reason
     * @since 1.5
     */
    public Type getGenericType() {
        if (getGenericSignature() != null)
            return getGenericInfo().getGenericType();
        else
            return getType();
    }

但这个是Type的类型,  它仅仅是一个空的接口:

/**
 * Type is the common superinterface for all types in the Java
 * programming language. These include raw types, parameterized types,
 * array types, type variables and primitive types.
 *
 * @since 1.5
 */


public interface Type {
}

它是Class类及泛型类型ParameterizedType的基类,  所以实现代码如下:


            Type type = field.getGenericType();
            if (!(type instanceof ParameterizedType))
            {
            throw new Exception("Parameterized type should be used");
            }
            ParameterizedType pt = (ParameterizedType)type;
            Type[] actualTypes = pt.getActualTypeArguments();
            if (actualTypes.length  > 1)
            {
            throw new Exception("Only One parameter type is support, actuall number is:" + actualTypes.length);
            }
            if (actualTypes.length  == 0)
            {
            throw new Exception("parameter type should be used");
            }
            unitClazz = (Class<?>)actualTypes[0];


unitClazz的结果就是等同于Person.class


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 17中,可以使用反射获取泛型类型。面是一种常见的方法: 1. 首先,通过反射获取目标类的Class对象。假设目标类为`MyClass`,可以使用`MyClass.class`或者`Class.forName("com.example.MyClass")`来获取。 2. 使用`getDeclaredField`方法获取目标字段的Field对象。假设目标字段为`myField`,可以使用`Class.getDeclaredField("myField")`来获取。 3. 通过Field对象的`getGenericType`方法获取字段的泛型类型。这将返回一个Type对象,表示字段的实际类型。 4. 如果字段的类型参数化类型(即包含泛型参数),可以通过Type对象的一些方法来获取泛型参数的信息。例如,可以使用`ParameterizedType`接口来获取参数化类型的原始类型泛型参数列表。 下面是一个示例代码,演示了如何使用反射获取泛型类型: ```java import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class Main { public static void main(String[] args) throws NoSuchFieldException { // 获取目标类的Class对象 Class<MyClass> clazz = MyClass.class; // 获取目标字段的Field对象 Field field = clazz.getDeclaredField("myField"); // 获取字段的泛型类型 Type fieldType = field.getGenericType(); // 如果字段的类型参数化类型 if (fieldType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) fieldType; // 获取参数化类型的原始类型 Type rawType = parameterizedType.getRawType(); System.out.println("Raw type: " + rawType); // 获取参数化类型泛型参数列表 Type[] typeArguments = parameterizedType.getActualTypeArguments(); for (Type typeArgument : typeArguments) { System.out.println("Type argument: " + typeArgument); } } } } class MyClass { private List<String> myField; } ``` 在上面的示例中,我们通过反射获取了`MyClass`类中名为`myField`的字段的泛型类型。输出结果如下: ``` Raw type: interface java.util.List Type argument: class java.lang.String ``` 这表明`myField`字段的类型是`List<String>`,其中`List`是原始类型,`String`是泛型参数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值