6

我正在尝试用 MethodHandle 替换反射调用,但 varargs 似乎无法处理。

我的反射调用程序目前看起来像这样:

public class Invoker {

    private final Method delegate;

    public Invoker(Method delegate) {
        this.delegate = delegate;
    }

    public Object execute(Object target, Object[] args) {
        return delegate.invoke(target, args);
    }
}

我目前重写它的尝试看起来像这样(Invoker暴露的接口必须保持不变):

public class Invoker {

    private final Method delegate;
    private final MethodHandle handle;

    public Invoker(Method delegate) {
        this.delegate = delegate;
        this.handle = MethodHandles.lookup().unreflect(delegate);
    }

    public Object execute(Object target, Object[] args) throws InvocationTargetException, IllegalAccessException {
        Object[] allArgs = Stream.concat(Stream.of(target), Stream.of(args)).toArray(Object[]::new);
        return handle.invokeWithArguments(allArgs);
    }
}

这在大多数情况下都很好用。但是可变参数打破了一切。例如有一个方法,如:

public String test(int i, String... args) {
    return ...;
}

和这样的论点:

Object[] args = new Object[] {10, new String[] {"aaa", "bbb"}};

并且execute如上所述实施将失败。asSpreader()我尝试了, MethodHandles.explicitCastArguments(),invoke而不是etc的各种组合,invokeWithArguments但没有成功。

我可以调用可变参数方法的唯一方法是提供内联参数而不是数组。例如

handle.invokeWithArguments(10, "aaa", "bbb")

但我不能这样做并保持Invoker它目前具有的通用性。

这真的不可能按照我尝试的方式进行吗?

更新: 在对各种场景进行基准测试后,我决定坚持使用反射,因为在所有测试用例invokeWithArguments中的表现都要差得多。

4

2 回答 2

6

似乎您只需要一次调用,.asFixedArity因为默认情况下java将创建方法句柄asVarargsCollector

public class Main {
    public static String test(int i, String... args) { return "works!"; }

    public static void main(String[] args) throws Throwable {
        Method method = Main.class.getMethod("test", int.class, String[].class);
        System.out.println(new Invoker(method).execute(null, new Object[]{1, new String[] {"foo", "bar"} }));
    }

    public static class Invoker {
        private final MethodHandle handle;

        public Invoker(final Method delegate) throws Exception {
            MethodHandle handle = MethodHandles.lookup().unreflect(delegate);
            if (Modifier.isStatic(delegate.getModifiers())) { // for easy static methods support
                handle = MethodHandles.dropArguments(handle, 0, Object.class);
            }
            this.handle = handle.asFixedArity();
        }

        public Object execute(Object target, Object[] args) throws Throwable {
            Object[] allArgs = new Object[args.length + 1];
            allArgs[0] = target;
            System.arraycopy(args, 0, allArgs, 1, args.length);
            return handle.invokeWithArguments(allArgs);
        }
    }
}

还有许多其他可能的解决方案,例如您可以向 Invoker 构造函数添加更多逻辑(静态工厂可能是一个好主意)并使用asType方法来准备您想要的签名,然后您应该能够调用它.invokeExact来获得小的性能提升。

您也可以继续使用Method;)

于 2018-08-30T16:07:21.500 回答
0

我完成了您的代码以重现您的问题,但它使用invokeWithArguments工作。也许我错过了什么?

public class Main {

    public String test(int i, String... args) {
        return i + Stream.of(args).collect(Collectors.joining());
    }


    public static void main(String[] args) throws Throwable {
        Main main = new Main();
        Method method = Main.class.getMethod(
            "test",
            int.class,
            String[].class)
        Invoker invoker = new Invoker(method);
        assertEquals("1foobar", invoker.execute(main, new Object[]{1, "foo", "bar"})); // Success
    }


    public static class Invoker {

        private final MethodHandle handle;

        public Invoker(final Method delegate) throws Exception {
            this.handle = MethodHandles.lookup().unreflect(delegate);
        }

        public Object execute(Object target, Object[] args) throws Throwable {
            // Add the target and all arguments in a new array
            Object[] allArgs = Stream.concat(Stream.of(new Object[]{target}), Stream.of(args))
                .toArray(Object[]::new);
            return handle.invokeWithArguments(allArgs);
        }
    }
}
于 2018-08-30T11:59:06.920 回答