[英]How to check that a method returns Collection<Foo> in Java?
I wish to a check if a method exists in an interface based on its signatures. 我希望检查接口中是否存在基于其签名的方法。
The signature that the method should have is: 该方法应具有的签名是:
Collection<Foo> methodName(Spam arg0, Eggs arg1, ...)
I can find the methods via Class.getMethods()
then find the name, parameters and return type respectively with method.getName()
, method.getParameterTypes()
and method.getReturnType()
. 我可以通过
Class.getMethods()
找到方法,然后分别使用method.getName()
, method.getParameterTypes()
和method.getReturnType()
查找名称,参数和返回类型。
But what do I compare the return type to in order to ensure that only methods that return Collection<Foo>
are chosen, and not other collections? 但是,为了确保只选择返回
Collection<Foo>
方法而不选择其他集合,我应该如何比较返回类型?
method.getReturnType().equals(Collection.class)
Since the above will be true for all methods that return a collection, not just for those that return a Foo
Collection. 由于上述内容对于返回集合的所有方法都是如此,而不仅仅是那些返回
Foo
集合的方法。
There is a method named public Type getGenericReturnType()
which can return (if it's the case) a ParameterizedType
. 有一个名为
public Type getGenericReturnType()
,它可以返回一个ParameterizedType
(如果是这种情况)。
A ParameterizedType
can give you more informations on a generic type such as Collection<Foo>
. ParameterizedType
可以为您提供有关泛型类型(如Collection<Foo>
更多信息。
In particular with the getActualTypeArguments()
method you can get the actual type for each parameter. 特别是使用
getActualTypeArguments()
方法,您可以获得每个参数的实际类型。
Here, ParameterizedType
represents Collection and getActualTypeArguments()
represents an array containing Foo 这里,
ParameterizedType
表示Collection, getActualTypeArguments()
表示包含Foo的数组
You can try this to list the parameters of your generic type : 您可以尝试这样列出泛型类型的参数:
Type returnType = method.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) returnType;
Type[] typeArguments = type.getActualTypeArguments();
for (Type typeArgument : typeArguments) {
Class typeArgClass = (Class) typeArgument;
System.out.println("typeArgClass = " + typeArgClass);
}
}
Sources : http://tutorials.jenkov.com/ 资料来源: http : //tutorials.jenkov.com/
通用类型参数在Java中不会保留(即,它只是一个编译时功能),因此您无法执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.