How to explicitly invoke default method from a dynamic Proxy?

前端 未结 6 822
一向
一向 2020-12-09 15:33

Since Java 8 interfaces could have default methods. I know how to invoke the method explicitly from the implementing method, i.e. (see Explicitly calling a default method i

6条回答
  •  既然无缘
    2020-12-09 15:58

    If all you have is an interface, and all you have access to is a class object is an interface that extends your base interface, and you want to call the default method without a real instance of a class that implements the interface, you can:

    Object target = Proxy.newProxyInstance(classLoader,
          new Class[]{exampleInterface}, (Object p, Method m, Object[] a) -> null);
    

    Create an instance of the interface, and then construct the MethodHandles.Lookup using reflection:

    Constructor lookupConstructor = 
        MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, Integer.TYPE);
    if (!lookupConstructor.isAccessible()) {
        lookupConstructor.setAccessible(true);
    }
    

    And then use that lookupConstructor to create a new instance of your interface that will allow private access to invokespecial. Then invoke the method on the fake proxy target you made earlier.

    lookupConstructor.newInstance(exampleInterface,
            MethodHandles.Lookup.PRIVATE)
            .unreflectSpecial(method, declaringClass)
            .bindTo(target)
            .invokeWithArguments(args);
    

提交回复
热议问题