从通用基接口的实例中检索类型参数 [英] Retrieving type parameters from an instance of a generic base interface

查看:131
本文介绍了从通用基接口的实例中检索类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定2个接口:

  public interface BaseInterface< T> {} 
public interface ExtendedInterface< T0,T1>扩展BaseInterface< T0> {}

以及具体的类:

  public class MyClass implements ExtendedInterface< String,Object> {} 

如何找到传递给BaseInterface接口的类型参数?



(我可以通过调用像

  MyClass.class来检索ExtendedInterface类型参数。 getGenericInterfaces()[0] .getActualTypeArguments()

但我无法找到简单的方法来回归到任何基本的通用接口并获得任何有意义的回传)。 解决方案

这个问题一般不易完全解决。例如,如果它是一个内部类,则还必须考虑包含类的类型参数...



因为仅仅使用泛型类型的反射很难Java本身提供了什么,我写了一个能够完成这项艰巨任务的库:gentyref。请参阅 http://code.google.com/p/gentyref/
For你的例子,使用gentyref,你可以这样做:

 输入myType = MyClass.class; 

//获取参数化类型,递归解析类型参数
类型baseType = GenericTypeReflector.getExactSuperType(myType,BaseInterface.class);

if(baseType instanceof Class<>){
// raw class,type parameters not known
// ...
} else {
ParameterizedType pBaseType =(ParameterizedType)baseType;
断言pBaseType.getRawType()== BaseInterface.class; //总是为真
类型typeParameterForBaseInterface = pBaseType.getActualTypeArguments()[0];
System.out.println(typeParameterForBaseInterface);
}


Given 2 interfaces:

public interface BaseInterface<T> { }
public interface ExtendedInterface<T0, T1> extends BaseInterface<T0> {}

and a concrete class:

public class MyClass implements ExtendedInterface<String, Object> { }

How do I find out the type parameter passed to the BaseInterface interface?

(I can retrieve the ExtendedInterface type parameters by calling something like

MyClass.class.getGenericInterfaces()[0].getActualTypeArguments()

but I can't spot an easy way to recurse into any base generic interfaces and get anything meaningful back).

解决方案

This problem is not easy to fully solve in general. For example, you also have to take type parameters of the containing class into account if it's an inner class,...

Because reflection over generic types is so hard using just what Java itself provides, I wrote a library that does the hard work: gentyref. See http://code.google.com/p/gentyref/ For your example, using gentyref, you can do:

Type myType = MyClass.class;

// get the parameterized type, recursively resolving type parameters
Type baseType = GenericTypeReflector.getExactSuperType(myType, BaseInterface.class);

if (baseType instanceof Class<?>) {
    // raw class, type parameters not known
    // ...
} else {
    ParameterizedType pBaseType = (ParameterizedType)baseType;
    assert pBaseType.getRawType() == BaseInterface.class; // always true
    Type typeParameterForBaseInterface = pBaseType.getActualTypeArguments()[0];
    System.out.println(typeParameterForBaseInterface);
}

这篇关于从通用基接口的实例中检索类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆