Tag: methodhandle

如何使用Object 数组调用MethodHandle.invokeExact()?

Java的MethodHandle.invokeExact(Object … args)采用可变长度的参数列表。 但是当我尝试传递一个Object []数组而不是一个列表时,我收到一个错误。 见下文: private void doIt() throws Throwable { Method meth = Foo.class.getDeclaredMethods()[0]; MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodHandle mh = lookup.unreflect(meth); Foo foo = new Foo(); String myStr = “aaa”; Integer myInt = new Integer(10); Object [] myArray = {foo, myStr, myInt}; mh.invokeExact(foo, myStr, myInt); // prints “Called aaa 10” mh.invokeExact(myArray); // […]

MethodHandle性能

我写了一个小基准测试来测试java.lang.invoke.MethodHandle , java.lang.reflect.Method和方法的直接调用的性能。 我读到MethodHandle.invoke()性能几乎与直接调用相同。 但我的测试结果显示另一个: MethodHandle调用比reflection慢大约三倍。 我的问题是什么? 可能这是一些JIT优化的结果? public class Main { public static final int COUNT = 100000000; static TestInstance test = new TestInstance(); static void testInvokeDynamic() throws NoSuchMethodException, IllegalAccessException { int [] ar = new int[COUNT]; MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodType mt = MethodType.methodType(int.class); MethodHandle handle = lookup.findStatic(TestInstance.class, “publicStaticMethod”, mt) ; try { […]

使用java.lang.invoke.MethodHandle调用私有方法

如何使用方法句柄调用私有方法? 据我所知,只有两种可公开访问的Lookup实例: MethodHandles.lookup() MethodHandles.publicLookup() 并且都不允许不受限制的私人访问。 有非公开的Lookup.IMPL_LOOKUP我的需求。 是否有一些公共方法来获取它(假设SecurityManager允许它)?

如何删除用作侦听器的lambda表达式/方法句柄?

Java 8引入了lambda表达式 ,这是一件好事。 但现在考虑重写这段代码: class B implements PropertyChangeListener { void listenToA(A a) { a.addPropertyChangeListener(this); } void propertyChange(PropertyChangeEvent evt) { switch(evt.getPropertyName()) { case “Property1”: doSomething(); break; case “Property2”: doSomethingElse(); case “Property1”: doSomething; break; break; } void doSomething() { } void doSomethingElse() { } } class A { final PropertyChangeSupport pcs = new PropertyChangeSupport(this); void addPropertyChangeListener(PropertyChangeListener listener) […]

是否可以将方法引用转换为MethodHandle?

是否可以将方法引用(例如SomeClass::someMethod )转换为MethodHandle实例? 我想要编译时检查的好处(确保存在类和方法)以及使用MethodHandle API内省方法的能力。 用例:当且仅当请求未被特定方法触发时(我要避免无限递归),我才需要执行代码。 我想进行编译时检查以确保类/方法存在但运行时检查以将调用者与方法进行比较。 那么回顾一下: 是否可以将方法引用转换为MethodHandle ?