如何从动态代理显式调用默认方法?

问题描述 投票:0回答:8

从 Java 8 接口开始可以有默认方法。 我知道如何从实现方法中显式调用该方法,即 (请参阅在 Java 中显式调用默认方法

但是我如何显式地使用反射调用默认方法(例如在代理上)?

示例:

interface ExampleMixin {

  String getText();

  default void printInfo(){
    System.out.println(getText());
  }
}

class Example {

  public static void main(String... args) throws Exception {

    Object target = new Object();

    Map<String, BiFunction<Object, Object[], Object>> behavior = new HashMap<>();

    ExampleMixin dynamic =
            (ExampleMixin) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{ExampleMixin.class}, (Object proxy, Method method, Object[] arguments) -> {

                //custom mixin behavior
                if(behavior.containsKey(method.getName())) {
                    return behavior.get(method.getName()).apply(target, arguments);
                //default mixin behavior
                } else if (method.isDefault()) {
                    //this block throws java.lang.IllegalAccessException: no private access for invokespecial
                    return MethodHandles.lookup()
                                        .in(method.getDeclaringClass())
                                        .unreflectSpecial(method, method.getDeclaringClass())
                                        .bindTo(target)
                                        .invokeWithArguments();
                //no mixin behavior
                } else if (ExampleMixin.class == method.getDeclaringClass()) {
                    throw new UnsupportedOperationException(method.getName() + " is not supported");
                //base class behavior
                } else{
                    return method.invoke(target, arguments);
                }
            });

    //define behavior for abstract method getText()
    behavior.put("getText", (o, a) -> o.toString() + " myText");

    System.out.println(dynamic.getClass());
    System.out.println(dynamic.toString());
    System.out.println(dynamic.getText());

    //print info should by default implementation
    dynamic.printInfo();
  }
}

编辑:我知道在如何反射性地调用Java 8默认方法中提出了类似的问题,但这并没有解决我的问题,原因有两个:

  • 该问题中描述的问题旨在如何通过反射来调用它一般 - 因此默认方法和重写方法之间没有区别 - 这很简单,您只需要一个实例。
  • 答案之一 - 使用方法句柄 - 只适用于令人讨厌的黑客(恕我直言),例如更改查找类字段的访问修饰符,这与“解决方案”属于同一类别,如下所示:使用 Java 更改私有静态最终字段反思很高兴知道这是可能的,但我不会在生产中使用它 - 我正在寻找一种“官方”方式来做到这一点。

IllegalAccessException
被扔进
unreflectSpecial

Caused by: java.lang.IllegalAccessException: no private access for invokespecial: interface example.ExampleMixin, from example.ExampleMixin/package
at java.lang.invoke.MemberName.makeAccessException(MemberName.java:852)
at java.lang.invoke.MethodHandles$Lookup.checkSpecialCaller(MethodHandles.java:1568)
at java.lang.invoke.MethodHandles$Lookup.unreflectSpecial(MethodHandles.java:1227)
at example.Example.lambda$main$0(Example.java:30)
at example.Example$$Lambda$1/1342443276.invoke(Unknown Source)
java reflection java-8 default-method
8个回答
16
投票

在 JDK 8 - 10 中使用

MethodHandle.Lookup
时,我也被类似的问题所困扰,它们的行为有所不同。 我已经在博客中详细介绍了正确的解决方案

此方法适用于 Java 8

在 Java 8 中,理想的方法是使用 hack,从

Lookup
:

访问包私有构造函数
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Constructor;
import java.lang.reflect.Proxy;

interface Duck {
    default void quack() {
        System.out.println("Quack");
    }
}

public class ProxyDemo {
    public static void main(String[] a) {
        Duck duck = (Duck) Proxy.newProxyInstance(
            Thread.currentThread().getContextClassLoader(),
            new Class[] { Duck.class },
            (proxy, method, args) -> {
                Constructor<Lookup> constructor = Lookup.class
                    .getDeclaredConstructor(Class.class);
                constructor.setAccessible(true);
                constructor.newInstance(Duck.class)
                    .in(Duck.class)
                    .unreflectSpecial(method, Duck.class)
                    .bindTo(proxy)
                    .invokeWithArguments(args);
                return null;
            }
        );

        duck.quack();
    }
}

这是唯一同时适用于私有可访问和私有不可访问接口的方法。但是,上述方法会对 JDK 内部进行非法反射访问,这在未来的 JDK 版本中或者在 JVM 上指定了

--illegal-access=deny
时将不再起作用。

此方法适用于 Java 9 和 10,但不适用于 8

import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Proxy;

interface Duck {
    default void quack() {
        System.out.println("Quack");
    }
}

public class ProxyDemo {
    public static void main(String[] a) {
        Duck duck = (Duck) Proxy.newProxyInstance(
            Thread.currentThread().getContextClassLoader(),
            new Class[] { Duck.class },
            (proxy, method, args) -> {
                MethodHandles.lookup()
                    .findSpecial( 
                         Duck.class, 
                         "quack",  
                         MethodType.methodType(void.class, new Class[0]),  
                         Duck.class)
                    .bindTo(proxy)
                    .invokeWithArguments(args);
                return null;
            }
        );

        duck.quack();
    }
}

解决方案

只需实现上述两个解决方案,并检查您的代码是否在 JDK 8 或更高版本的 JDK 上运行,就可以了。直到你不再:)


10
投票

如果您使用具体的 impl 类作为 LookupClass 和 invokeSpecial 的调用者,它应该正确调用接口的默认实现(不需要对私有访问进行黑客攻击):

Example target = new Example();
...

Class targetClass = target.getClass();
return MethodHandles.lookup()
                    .in(targetClass)
                    .unreflectSpecial(method, targetClass)
                    .bindTo(target)
                    .invokeWithArguments();

当然,只有当您有对实现接口的具体对象的引用时,这才有效。

编辑:只有当相关类(上面代码中的示例)可以从调用者代码私有访问时,此解决方案才有效,例如一个匿名内部类。

MethodHandles/Lookup 类的当前实现不允许在当前调用者类不能私有访问的任何类上调用 invokeSpecial。有各种可用的解决方法,但所有这些都需要使用反射来使构造函数/方法可访问,如果安装了 SecurityManager,这可能会失败。


10
投票

在 Java 16 中(来自 文档,其中还有更复杂的示例):

Object proxy = Proxy.newProxyInstance(loader, new Class[] { A.class },
        (o, m, params) -> {
            if (m.isDefault()) {
                // if it's a default method, invoke it
                return InvocationHandler.invokeDefault(o, m, params);
            }
        });
}

2
投票

如果您拥有的只是一个接口,并且您所能访问的只是一个类对象,并且您想要调用默认方法而无需实现该接口的类的真实实例,那么您可以:

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

创建接口的实例,然后使用反射构造MethodHandles.Lookup:

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

然后使用该

lookupConstructor
创建接口的新实例,该实例将允许对
invokespecial
进行私有访问。然后在您之前创建的假代理
target
上调用该方法。

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

2
投票

T。 Neidhart 的答案几乎有效,但我得到了 java.lang.IllegalAccessException: no private access for invokespecial

更改为使用

MethodHandles.privateLookupIn(...)
解决了它

return MethodHandles.privateLookupIn(clazz,MethodHandles.lookup())
                        .in(clazz)
                        .unreflectSpecial(method, clazz)
                        .bindTo(proxy)
                        .invokeWithArguments(args);

这是一个完整的示例,其想法是扩展提供的 IMap 的用户可以使用他的自定义界面访问嵌套的嵌套地图

interface IMap {
    Object get(String key);

    default <T> T getAsAny(String key){
        return (T)get(key);
    }


    default <T extends IMap> T getNestedAs(String key, Class<T> clazz) {
        Map<String,Object> nested = getAsAny(key);
        return (T)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{clazz},  (proxy, method, args) -> {
                    if (method.getName().equals("get")){
                        return nested.get(args[0]);
                    }
                    return MethodHandles.privateLookupIn(clazz, MethodHandles.lookup())
                            .in(clazz)
                            .unreflectSpecial(method, clazz)
                            .bindTo(proxy)
                            .invokeWithArguments(args);
                }
        );
    }
}

interface IMyMap extends IMap{

    default Integer getAsInt(String key){
        return getAsAny(key);
    }
    default IMyMap getNested(String key){
        return getNestedAs(key,IMyMap.class);
    }
}

@Test
public void test(){
    var data =Map.of("strKey","strValue", "nstKey", Map.of("intKey",42));
    IMyMap base = data::get;

    IMyMap myMap = base.getNested("nstKey");
    System.out.println( myMap.getAsInt("intKey"));
}

1
投票

用途:

Object result = MethodHandles.lookup()
    .in(method.getDeclaringClass())
    .unreflectSpecial(method, method.getDeclaringClass())
    .bindTo(target)
    .invokeWithArguments();

1
投票

我们可以看到spring是如何处理默认方法的。

  1. 首先尝试调用公共方法
    MethodHandles.privateLookupIn(Class,Lookup)
    。这应该在 jdk9+ 上成功。
  2. 尝试使用包私有构造函数创建一个 Lookup
    MethodHandles.Lookup(Class)
  3. 回退到 MethodHandles.lookup().findSpecial(...)

https://github.com/spring-projects/spring-data-commons/blob/2.1.8.RELEASE/src/main/java/org/springframework/data/projection/DefaultMethodInvokingMethodInterceptor.java


0
投票

Lukas 的答案适用于 Android 8+(早期版本没有默认方法),但依赖于后来的 Android 版本中被阻止的私有 API。幸运的是,替代构造函数也可以工作,并且目前处于灰名单中(不受支持)。可以在此处查看示例(用 Kotlin 编写)。

@get:RequiresApi(26)
private val newLookup by lazy @TargetApi(26) {
    MethodHandles.Lookup::class.java.getDeclaredConstructor(Class::class.java, Int::class.java).apply {
        isAccessible = true
    }
}

@RequiresApi(26)
fun InvocationHandler.invokeDefault(proxy: Any, method: Method, vararg args: Any?) =
    newLookup.newInstance(method.declaringClass, 0xf)   // ALL_MODES
        .unreflectSpecial(method, method.declaringClass)
        .bindTo(proxy)
        .invokeWithArguments(*args)
© www.soinside.com 2019 - 2024. All rights reserved.