简体   繁体   English

如何使用Java中的反射查找在类中使用其他接口扩展其他类的所有接口

[英]How to find all interfaces in class that extends other classes with other interfaces using reflection in java

for example I have: 例如我有:

interface IA;
interface IB;

public class B implements IB;
public class A extends B implements IA;

how can I find in A.class all implemented interfaces in extended B.class too?, method Class<?> getInterfaces() returns only interfaces in A class not in extended class. 如何可以在找到A.class在扩展所有实现的接口B.class太?,方法Class<?> getInterfaces()中仅返回接口A类不在扩展的类。

Get the superclass and its interfaces 获取超类及其接口

Class<?> clazz = A.class;
Class<?>[] interfaces = clazz.getSuperclass().getInterfaces();
// add interfaces to some larger list

Do this recursively until the superclass is Object or null . 递归执行此操作,直到超类为Objectnull为止。

If this Class represents either the Object class, an interface, a primitive type, or void , then null is returned. 如果该Class表示Object类,接口,原始类型或void ,则返回null

You have to loop, calling getInterfaces on A , then use getSuperclass to get its super class, and then do that again, etc., until getSuperclass returns null . 您必须循环,在A上调用getInterfaces ,然后使用getSuperclass获取其超类,然后再次执行此操作, getSuperclass ,直到getSuperclass返回null为止。

List<Class<?>> list = new LinkedList<Class<?>>();
Class<?> cls = A.class;
while (cls != null) {
    // Call cls.getInterfaces, add result to list
    // ...

    // Go to its parent
    cls = cls.getSuperclass();
}

Guava Solution: 番石榴解决方案:

Proxies.java Proxies.java

public static TypeToken.TypeSet getTypes(@Nonnull final Class cls)
{
    return TypeToken.of(cls).getTypes();
}

public static TypeToken subClassesOf(@Nonnull final Class superClass, @Nonnull final Set<TypeToken> typeTokens)
{
    for (final TypeToken tt : typeTokens)
    {
        if (tt.getRawType().getSuperclass() == null)
        {
            return tt;
        }
        {
            return subClassesOf(superClass, tt.getTypes().interfaces());
        }
    }
    return null;
}

Here is how you call it: 这是你的称呼:

    final Class superClass = // super class you want the subclass Interface of
    final TypeToken tt = TypeToken.of(superClass.getClass());
    final TypeToken tti = Proxies.subClassesOf(superClass.getClass(),tt.getTypes().interfaces());
    final Class subTypeInterface = tti.getRawType();

I use this to pull Annotations from a DyanmicProxy instance where the Annotations are on the specialized SubType interface. 我使用它从DyanmicProxy实例中提取Annotations ,在DyanmicProxy实例中, Annotations位于专用的SubType接口上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM