[英]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
. 递归执行此操作,直到超类为Object
或null
为止。
If this
Class
represents either theObject
class, an interface, a primitive type, orvoid
, thennull
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();
}
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.