简体   繁体   English

带有超类参数的Java getMethod方法

[英]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. 就是你的方法所期望的。

I'm guessing you want getDeclaredMethods() . 我猜你想要getDeclaredMethods() Here is an example . 这是一个例子 You can dig through the list of methods and pick the one you want by name. 您可以浏览方法列表并按名称选择所需方法。 Whether or not this is robust or a good idea is another question. 这是一个强大的还是一个好主意是另一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM