0

I want to use the method MethodHandleNatives.getTargetMethod(MethodHandle)AccessibleObject. The class MethodHandleNatives is not public. So does anybody know how I can do that?

I know that its possible to access private methods and fields via reflections, so I am asking, if this is also possible.

Thanks.

assylias
  • 321,522
  • 82
  • 660
  • 783
Thorben
  • 953
  • 13
  • 28

1 Answers1

1

I have found a solution.
It is not straight forward but it works =)

MethodHandle mh; // a MethodHandle Object
Class<?> mhn;
    try {
        mhn = Class.forName("java.lang.invoke.MethodHandleNatives");
        Constructor<?> con = mhn.getDeclaredConstructor();
        con.setAccessible(true);
        Object mhnInstance = con.newInstance();
        Method getTargetMethod = mhn.getDeclaredMethod("getTargetMethod", new Class<?>[]{MethodHandle.class});
        getTargetMethod.setAccessible(true);
        Method inside = (Method) getTargetMethod.invoke(mhnInstance, mh);
        System.out.println("INSIDE = " + inside.toGenericString());

    } catch (Throwable e) {
        e.printStackTrace();
    }
Thorben
  • 953
  • 13
  • 28
  • I've had to use reflection hacks like this before. It's ugly and should be avoided, but sometimes there really is no other way without a LOT of copy and paste. Another option if a class or method is package-private is to declare a wrapper class in the same package in your project with everything public, and forward requests to the package-protected class. –  Apr 16 '13 at 22:28