Java getMethod在方法中具有超类参数 [英] Java getMethod with superclass parameters in method

查看:50
本文介绍了Java getMethod在方法中具有超类参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出:

class A
{
    public void m(List l) { ... }
}

假设我想通过反射调用方法 m ,将ArrayList作为参数传递给 m :

Let's say I want to invoke method m with reflection, passing an ArrayList as the parameter to m:

List myList = new ArrayList();
A a = new A();
Method method = A.class.getMethod("m", new Class[] { myList.getClass() });
method.invoke(a, Object[] { myList });

第3行的 getMethod 将抛出 NoSuchMethodException ,因为myList的运行时类型是ArrayList,而不是List.

The getMethod on line 3 will throw NoSuchMethodException because the runtime type of myList is ArrayList, not List.

是否有一种很好的通用方法,不需要了解A类的参数类型?

Is there a good generic way around this that doesn't require knowledge of class A's parameter types?

推荐答案

如果您知道类型为 List ,则使用 List.class 作为参数.

If you know the type is List, then use List.class as argument.

如果您事先不知道类型,请想象您有:

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?

如果需要,可以使用 Class.getInterfaces() Class.getSuperclass(),但这是因情况而异的.

If you want, you can use Class.getInterfaces() or Class.getSuperclass() but this is case-specific.

您在这里可以做的是:

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 getMethod在方法中具有超类参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆