[英]Java getMethod with superclass parameters in method
Given: 鉴于:
class A
{
public void m(List l) { ... }
}
Let's say I want to invoke method m
with reflection, passing an ArrayList as the parameter to m
: 假设我想用反射调用方法m
,将ArrayList作为参数传递给m
:
List myList = new ArrayList();
A a = new A();
Method method = A.class.getMethod("m", new Class[] { myList.getClass() });
method.invoke(a, Object[] { myList });
The getMethod
on line 3 will throw NoSuchMethodException
because the runtime type of myList is ArrayList, not List. 第3行的getMethod
将抛出NoSuchMethodException
因为myList的运行时类型是ArrayList,而不是List。
Is there a good generic way around this that doesn't require knowledge of class A's parameter types? 有没有一个很好的通用方法,不需要知道A类的参数类型?
If you know the type is List
, then use List.class
as argument. 如果您知道类型是List
,那么使用List.class
作为参数。
If you don't know the type in advance, imagine you have: 如果您事先不知道类型,请想象您有:
public void m(List l) {
// all lists
}
public void m(ArrayList l) {
// only array lists
}
Which method should the reflection invoke, if there is any automatic way? 如果有任何自动方式,反射会调用哪种方法?
If you want, you can use Class.getInterfaces()
or Class.getSuperclass()
but this is case-specific. 如果需要,可以使用Class.getInterfaces()
或Class.getSuperclass()
但这是特定于案例的。
What you can do here is: 你在这里可以做的是:
public void invoke(Object targetObject, Object[] parameters,
String methodName) {
for (Method method : targetObject.getClass().getMethods()) {
if (!method.getName().equals(methodName)) {
continue;
}
Class<?>[] parameterTypes = method.getParameterTypes();
boolean matches = true;
for (int i = 0; i < parameterTypes.length; i++) {
if (!parameterTypes[i].isAssignableFrom(parameters[i]
.getClass())) {
matches = false;
break;
}
}
if (matches) {
// obtain a Class[] based on the passed arguments as Object[]
method.invoke(targetObject, parametersClasses);
}
}
}
请参阅java.beans.Expression和java.beans.Statement。
Instead of myList.getClass()
, why not just pass in List.class
? 而不是myList.getClass()
,为什么不直接传入List.class
? That is what your method is expecting. 这就是你的方法所期望的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.