Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have this class:
package com.gmail.inverseconduit.jchatexchange.assets;

import jchatexchange.util.User;

public class UserFactory implements jchatexchange.factory.Factory {

    private boolean cnu(User user) {
        [implementation dependant on #cnuz(User)]
    }

    private int cnuz(User user) {
        [my implementation]
    }

    @Override
    public User createNewUser(int id) {
        [my implementation]
    }

    // Other methods

}


I want to obtain a MethodHandle of each of the three methods in another class, so I used:

Java
class Baz {

    public static void main(String..$) {
        Lookup myLookup = MethodHandles.lookup();
        UserFactory foo = new UserFactory(); // test
    
        try {
            MethodType signature = MethodType.methodType(boolean.class, User.class);
            MethodHandle pmh = lookup.findVirtual(UserFactory.class, "cnu", signature);
            // ??? what now? I can't find any method in Java API that does what I need -
            // to actually invoke a private method with this.
    
            // I would have expected this to work:
            boolean cnuResult = pmh.bindTo(foo).invoke();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


I need Lookup.IMPL_LOOKUP, but there is no public way that allows it. What should I use in order for this to work?

Additional note: MethodHandles are added in Java 6, but I'm using Java 8, so any tricks related to Java 8 will be appreciated as well.
Posted
Updated 13-Dec-14 23:06pm
v4

1 solution

You can use Lookup.unreflect[^]:
Java
public static void main(String..$) {
    Lookup myLookup = MethodHandles.lookup();
    UserFactory foo = new UserFactory(); // test
    User baz = new User();
    
    try {
        Method m = UserFactory.class.getDeclaredMethod("cnu", User.class);
        m.setAccessible(true);
        MethodHandle pmh = myLookup.unreflect(m);
        boolean b = (boolean)pmh.invoke(foo, baz);
           
    } catch (Exception e) {
        e.printStackTrace();
    } catch (Throwable e) {
      	e.printStackTrace();
    }
}   
 
Share this answer
 
Comments
Unihedron 14-Dec-14 6:03am    
Wow, it works, thank you so much!
Thomas Daniels 14-Dec-14 6:04am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900