MethodHandle是Java7引入的一种机制,主要是为了JVM支持动态语言。

共有方法调用

首先,演示一下最基本的MethodHandle使用。

第一步:创建查找对象:Lookup

  1. // 获取Look用于查找方法句柄
  2. MethodHandles.Lookup lookup = MethodHandles.lookup();

第二步:创建方法类型:MethodType

构造方法的返回值类型,参数类型

  1. // 方法类型,描述返回值和参数,第一个参数为返回值类型,void则为void.class。
  2. //第二个参数开始为被调用方法的参数类型
  3. MethodType mt = MethodType.methodType(boolean.class, String.class, int.class);

第三步:查找方法句柄

Lookup的findVirtual查找成员方法

  1. //查找方法句柄,参数1:调用类,参数2:方法名,参数3:方法类型
  2. MethodHandle handle = lookup.findVirtual(String.class, "startsWith", mt);

第四步:方法调用

通过MehodHandle的invoke方法执行,并返回结果

  1. //方法调用,参数1:实例,参数2..n:方法参数
  2. Boolean value = (Boolean)handle.invoke("the i am in the room", "the", 0);

私有方法调用

  1. public static void main(String..) {
  2. Lookup myLookup = MethodHandles.lookup();
  3. UserFactory foo = new UserFactory(); // test
  4. User baz = new User();
  5. try {
  6. Method m = UserFactory.class.getDeclaredMethod("cnu", User.class);
  7. m.setAccessible(true);
  8. MethodHandle pmh = myLookup.unreflect(m);
  9. boolean b = (boolean)pmh.invoke(foo, baz);
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. } catch (Throwable e) {
  13. e.printStackTrace();
  14. }
  15. }

以上就是一个简单的调用示例。

核心代码解读

上面我们展示了一个最进本MethodHandle方式的方法调用,下面我们将对其中用到的主要类进行介绍。这些主要的类包含MethodType,MethodHandle,MethodHandles及Lookup。

MethodType

首先,我们来看看Methodtype,MethodType是用来封装方法输入输出类型的,包含方法的返回和方法的参数。MethodType构造方法为私有,只能通过MethodType提供的静态工具方法来获取实例

  1. /**
  2. * Constructor that performs no copying or validation.
  3. * Should only be called from the factory method makeImpl
  4. */
  5. private MethodType(Class<?> rtype, Class<?>[] ptypes) {
  6. this.rtype = rtype;
  7. this.ptypes = ptypes;
  8. }

MethodType中常用的工具方法有:

  • 大于一个参数
  1. public static MethodType methodType(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes) {
  2. Class<?>[] ptypes1 = new Class<?>[1+ptypes.length];
  3. ptypes1[0] = ptype0;
  4. System.arraycopy(ptypes, 0, ptypes1, 1, ptypes.length);
  5. return makeImpl(rtype, ptypes1, true);
  6. }
  • 无参数
  1. public static MethodType methodType(Class<?> rtype) {
  2. return makeImpl(rtype, NO_PTYPES, true);
  3. }

工具方法都通过makeImple方法来封装MethodType实例,指北君带领大家来看看makeImple中做了哪些事情:

  1. 参数检查
    • 返回值的类型不能为null,如果无返回使用void.class
    • 参数类型不能为null,且不能为void.class
  2. 使用缓存表缓存MethodType实例,优化处理
  3. 如果非信任模式(trusted==false),则克隆参数数组

这里需要注意MethodType重写了hashCode方法,从逻辑看参数数组克隆不影响同类型的缓存机制。

  1. static MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
  2. if (ptypes.length == 0) {
  3. ptypes = NO_PTYPES; trusted = true;
  4. }
  5. MethodType primordialMT = new MethodType(rtype, ptypes);
  6. MethodType mt = internTable.get(primordialMT);
  7. if (mt != null)
  8. return mt;
  9. // promote the object to the Real Thing, and reprobe
  10. MethodType.checkRtype(rtype);
  11. if (trusted) {
  12. MethodType.checkPtypes(ptypes);
  13. mt = primordialMT;
  14. } else {
  15. // Make defensive copy then validate
  16. ptypes = Arrays.copyOf(ptypes, ptypes.length);
  17. MethodType.checkPtypes(ptypes);
  18. mt = new MethodType(rtype, ptypes);
  19. }
  20. mt.form = MethodTypeForm.findForm(mt);
  21. return internTable.add(mt);
  22. }

除了静态工具方法外,MethodType还有几个实例方法,主要为差异性较小的MethodType提供快速获取实例的方法。包含:

  • changeParameterType
  • insertParameterTypes
  • appendParameterTypes
  • dropParameterTypes

MethodHandle

MethodHandle为抽象类,但是里面提供了大量的原生方法,提供底层访问,也是方法调用的核心逻辑。这部分涉及MethodHandle的机制实现,对于使用功能来说就不在此展开了。

  1. @HotSpotIntrinsicCandidate
  2. public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
  3. @HotSpotIntrinsicCandidate
  4. public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;

方法调用机制 - 图1

MethodHandles, Lookup

MethodHandles不是MethodHandle的实现,他提供工具用于帮助获取MethodHandle,我们主要使用到lookup(),publicLookup()

@CallerSensitive注解,可以使Reflection.getCallerClass()获取到调用lookup()方法的类

  1. @CallerSensitive
  2. @ForceInline // to ensure Reflection.getCallerClass optimization
  3. public static Lookup lookup() {
  4. return new Lookup(Reflection.getCallerClass());
  5. }
  6. public static Lookup publicLookup() {
  7. return Lookup.PUBLIC_LOOKUP;
  8. }

Lookup构造方法主要传入两个参数:

  1. lookupClass搜寻的类,
  2. allowedModes:许可模式。

最后,通过Lookup的findXXX获取到MethodHandle,详细说明见下表:
方法调用机制 - 图2

小结

关于MethodHandle的基本使用就基本讲完,这里附上一张类图便大家理解:
方法调用机制 - 图3