首页 > 其他 > 详细

执行接口默认方法

时间:2019-03-18 15:26:44      阅读:179      评论:0      收藏:0      [点我收藏+]

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;
}
}

执行接口默认方法

原文:https://www.cnblogs.com/sidesky/p/10552335.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!