我希望检查接口中是否存在基于其签名的方法.
该方法应具有的签名是:
Collection<Foo> methodName(Spam arg0, Eggs arg1, ...)
Run Code Online (Sandbox Code Playgroud)
我可以找到方法Class.getMethods()
然后分别找到名称,参数和返回类型method.getName(), method.getParameterTypes()和method.getReturnType().
但是,为了确保只Collection<Foo>选择返回的方法,而不是其他集合,我应该将返回类型与之进行比较?
method.getReturnType().equals(Collection.class)
Run Code Online (Sandbox Code Playgroud)
由于上述内容对于返回集合的所有方法都是如此,而不仅仅是那些返回FooCollection的方法.
有一个命名的方法public Type getGenericReturnType()可以返回(如果是这种情况)a ParameterizedType.
A ParameterizedType可以为您提供有关泛型类型的更多信息,例如Collection<Foo>.
特别是使用该getActualTypeArguments()方法,您可以获得每个参数的实际类型.
这里,ParameterizedType表示Collection并getActualTypeArguments()表示包含Foo的数组
您可以尝试这样列出泛型类型的参数:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
资料来源: http ://tutorials.jenkov.com/
| 归档时间: |
|
| 查看次数: |
2557 次 |
| 最近记录: |