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

查看:21
本文介绍了方法中带有超类参数的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天全站免登陆