java reflect method_将java.lang.reflect.Method强制转换为功能接口

很难找到该主题的任何线索.我只能找到有关将一个功能接口转换为另一个功能接口的问题,以及一些有关Java中类型转换的文章.不是我要找的东西.

This的问题是关于转换lambda→方法,我想相反,将Method转换为任何功能接口,例如,转换为Consumer.

我发现的方法是围绕Method#invoke方法创建一个lambda适配器:

public void registerCallbacks(final Object annotated) {

Class clazz = annotated.getClass();

for (Method method : clazz.getDeclaredMethods()) {

if (method.isAnnotationPresent(Callback.class)) {

Callback registration = method.getAnnotation(Callback.class);

List warnings = new ArrayList<>(3);

if (!Modifier.isPublic(method.getModifiers()))

warnings.add(String.format("Method %s must be public", method));

if (method.getParameterCount() != 1)

warnings.add(String.format("Method %s must consume only one argument", method));

if (method.getParameterCount() == 1 && !method.getParameterTypes()[0].equals(Integer.class))

warnings.add(String.format("Method %s must consume %s", method, Integer.class));

if (!warnings.isEmpty()) {

warnings.forEach(log::warn);

continue;

}

CALLBACKS_MAPPER.registerCallback((param) -> {

try {

method.invoke(annotated, param);

} catch (IllegalAccessException | InvocationTargetException e) {

// Should not happen due to checks before.

log.warn(String.format("Could not invoke %s on %s with %s", method, annotated, param), e);

}

});

log.info("Registered {} as a callback", method);

}

}

}

但是我想避免写

CALLBACKS_MAPPER.registerCallback((param) -> {

try {

method.invoke(annotated, param);

} catch (IllegalAccessException | InvocationTargetException e) {

// Should not happen due to checks before.

log.warn(String.format("Could not invoke %s on %s with %s", method, annotated, param), e);

}

});

赞成更简单的事情,例如

CALLBACKS_MAPPER.registerCallback(SomeApacheLib.methodToFunction(annotated, method));

?因此,有没有办法将旧的Java 1.1反射库映射到较新的Java 8功能接口,还是我很笨,上面提到的用lambda的解决方案就可以了?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值