[英]Java Reflection - object graph
I have a problem to solve :) Let's say that I have such structure: 我有一个要解决的问题:)假设我有这样的结构:
Interfaces: 接口:
public interface RestServiceConverter<S, D> {
public D convert(S input);
}
public interface AdvancedRestServiceConverter<D, F, S> extends RestServiceConverter<S, D> {
}
Classes: 类别:
public class TestConverter extends SecondAbstractLevel<Integer> {
@Override
public ConvertedResult<String> convert(RawResult input) {
return null;
}
}
public abstract class AbstractTestConverter<S, D> extends SecondAbstractLevel {
}
public abstract class SecondAbstractLevel<T>
implements AdvancedRestServiceConverter<ConvertedResult<String>, Integer, RawResult> {
}
Question: is there any simple way to find what types are parameters from RestServiceConverter (look that params are not explicite in this interface but in AdvancedRestServiceConverter in reverse order) starting from TestConverter? 问:从TestConverter开始,有没有一种简单的方法可以从RestServiceConverter中查找参数的类型(看起来参数在此接口中不是显式的,而在AdvancedRestServiceConverter中是相反的)? Maybe some library can help mi with that.
也许一些图书馆可以帮助我。 I'm building some functionality in my code, where I have to check if field in some class is same as the second parameter.
我在代码中构建了一些功能,必须在其中检查某些类中的字段是否与第二个参数相同。
Let say I need method like this 假设我需要这样的方法
findParameter(TestConverter.class, RestServiceConverter.class)
which returns array 返回数组
[RawType, ConvertedResult<String>]
Thanks for help. 感谢帮助。
Unfortunately not. 不幸的是没有。 Java has this rather unfortunate thing known as "type erasure", which means that in your bytecode,
RestServiceConverter<S, D>
just becomes RestServiceConverter
for any S
and D
you put there. Java有一个相当不幸的东西,称为“类型擦除”,这意味着在您的字节码中,
RestServiceConverter<S, D>
变成您放置在其中的任何S
和D
RestServiceConverter
。
How a lot of third-party libraries will get around this is to have the implementation take whatever Class<?>
instances it needs in order to do its job. 有多少第三方库可以解决这个问题,就是使实现采用执行其工作所需的任何
Class<?>
实例。
Actually, in your specific case, this should be possible (if I got you right). 实际上,在您的特定情况下,这应该可行(如果我说对了)。 You have supertypes that will preserve the generic information, so erasure won't bother you.
您具有保留通用信息的超类型,因此擦除不会打扰您。
Library called GenTyRef , and my AnnotatedType -enabled fork GeAnTyRef (both available in Maven Central ), can easily get you what you need: 名为GenTyRef的库以及启用了AnnotatedType的 fork GeAnTyRef (均可在Maven Central中使用 )可以轻松获得所需的内容:
ParameterizedType exact = (ParameterizedType) GenericTypeReflector.getExactSuperType(TestConverter.class, RestServiceConverter.class);
Type[] typeParams = exact.getActualTypeArguments(); //returning exactly what you asked for
Shamelessly linking to my answer on a similar question. 无耻地链接到我对类似问题的回答。 Since you have your generic, say
E
, at hand, you can cast object.getClass()
to Class<E>
, which sould give you the requested types. 由于您拥有通用名称,例如
E
,因此可以将object.getClass()
为Class<E>
,从而为您提供所需的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.