如何在运行时调用方法的方法?

时间:2018-11-01 07:00:05

标签: java

我知道使用反射我们可以在运行时调用方法。我有一个要求obj.getMethod1().getMethod2().getMethod3()在运行时被调用。仅在运行时知道方法名称。运行期间方法的数量也有所不同。有时可以是obj.getMethod1().getMethod2()

目前,我正在通过以下数组进行处理

 obj=initialObj;
 for(i=0;i<arrayValue.length;i++){
     tempobj=obj.getClass.getMethod(arrayValue[i])// arrayValue contains method name
     obj=tempobj;
 }

还有其他更好的方法吗?

2 个答案:

答案 0 :(得分:1)

假设您的方法没有参数,则可以执行以下操作:

public static Object callChainedMethods(Object obj, String[] methodNames) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Class<?> type = obj.getClass();
    Object objectOnWhichToCallMethod = obj;
    for (String methodName : methodNames) {
        Method m = type.getMethod(methodName);
        objectOnWhichToCallMethod = m.invoke(objectOnWhichToCallMethod);
        type = objectOnWhichToCallMethod.getClass();
    }
    return objectOnWhichToCallMethod;
}

如果您不需要返回最终的返回值:

public static void callChainedMethods(Object obj, String[] methodNames) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Class<?> type = obj.getClass();
    Object objectOnWhichToCallMethod = obj;
    for (String methodName : methodNames) {
        Method m = type.getMethod(methodName);
        objectOnWhichToCallMethod = m.invoke(objectOnWhichToCallMethod);
        type = objectOnWhichToCallMethod.getClass();
    }
}

例如:

String[] methods = {"toString", "getClass", "getClass"};
System.out.println(callChainedMethods((Integer)10, methods));
// prints "class java.lang.Class"
// because it is calling ((Integer)10).toString().getClass().getClass()

答案 1 :(得分:0)

这是util类,其中包含常用方法:

public final class ReflectionUtils {
    public static <T> T invokeMethod(Object obj, String name, Class<?>[] types, Object... values) throws Throwable {
        try {
            Method method = getMethod(obj.getClass(), name, types);
            method.setAccessible(true);
            return (T)method.invoke(obj, values);
        } catch(InvocationTargetException e) {
            throw e.getTargetException();
        }
    }

    private static Method getMethod(Class<?> cls, String name, Class<?>... types) throws NoSuchMethodException {
        Method method = null;

        while (method == null && cls != null) {
            try {
                method = cls.getDeclaredMethod(name, types);
            } catch(NoSuchMethodException ignored) {
                cls = cls.getSuperclass();
            }
        }

        if (method == null) {
            throw new NoSuchMethodException();
        }

        return method;
    }
}

这是呼叫obj.getMethod1().getMethod2().getMethod3()的方法:

public static Object invokeMethods(Object obj, String... methodNames) throws Throwable {
    for (String methodName : methodNames)
        obj = ReflectionUtils.invokeMethod(obj, methodName, null);
    return obj;
}

客户端代码可能如下所示:

Object res = invokeMethods(obj, "getMethod1", "getMethod2", "getMethod2");