zoukankan      html  css  js  c++  java
  • 执行接口默认方法

    public class YafBeanManager implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
    }

    public Object invokeMethod(YafMethod yafMethod, Object[] args, Method method) throws Throwable {
    if (yafMethod != null) {
    Object bean = applicationContext.getBean(yafMethod.getClazz());
    Method yafM = yafMethod.getMethod();
    Object returnObj = yafM.invoke(bean, args);
    return returnObj;
    }

    // 没有提供扩展, 执行扩展点的默认实现
    if (method.isDefault()) {
    Object bean = applicationContext.getBean("save");
    Class<?> interfaceCls = method.getDeclaringClass();
    Object target = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
    new Class[]{interfaceCls},
    (proxy, m, arguments) -> {
    m.setAccessible(true);
    return m.invoke(bean, arguments);
    }
    );


    MethodHandles.Lookup lookup = MethodHandles.lookup().in(target.getClass());

    // 修改 lookup 实例中的 allowedModes, 否则会抛异常导致调不了 default 方法
    Field field = lookup.getClass().getDeclaredField("allowedModes");
    field.setAccessible(true);

    // 改掉这个字段的 final
    Field modifierField = Field.class.getDeclaredField("modifiers");
    modifierField.setAccessible(true);
    modifierField.set(field, field.getModifiers() ^ Modifier.FINAL);

    // 设置allowedModes
    field.set(lookup, -1);

    return lookup.unreflectSpecial(method, interfaceCls)
    .bindTo(target)
    .invokeWithArguments(args);
    }

    return null;
    }
    }

  • 相关阅读:
    位运算专题
    状态压缩DP SRM 667 Div1 OrderOfOperations 250
    Codeforces Round #319 (Div. 2)
    (好题)树状数组+离散化+DFS序+离线/莫队 HDOJ 4358 Boring counting
    线段树+离散化 POJ 2528 Mayor's posters
    stack(单调栈) POJ 2082 Terrible Sets
    queue POJ 2259 Team Queue
    并查集 POJ 1703 Find them, Catch them
    线段树/树状数组 POJ 2182 Lost Cows
    01背包入门题集
  • 原文地址:https://www.cnblogs.com/sidesky/p/10552335.html
Copyright © 2011-2022 走看看