我有一个想要通过反射调用的方法:
@Override
public SELF withLogConsumer(Consumer<OutputFrame> consumer) {
this.logConsumers.add(consumer);
return self();
}
如果没有反射(reflection),我会使用类似以下内容来调用此方法:
Container c = new Container().withLogConsumer(SimpleClass::log);
public void log(OutputFrame frame) {
String msg = frame.getUtf8String();
if (msg.endsWith("\n"))
msg = msg.substring(0, msg.length() - 1);
Log.info(this.clazz, "output", msg);
}
使用反射我希望能够做到:
Constructor<?> ctor = SimpleClass.class.getConstructor();
Object object = ctor.newInstance();
Method withLogConsumer = object.getClass().getMethod("withLogConsumer", Consumer<OutputFrame>.class);
withLogConsumer.invoke(object, SimpleClass::log)
这有两个问题我似乎也找不到答案:
- 如何使用反射创建接受通用方法参数类型的方法? (就像我的方法接受 ArrayList 一样)
- 如何使用双冒号语法传入方法?
最佳答案
- 忽略泛型类型;使用原始的、已删除的、非通用类型。
Method withLogConsumer = object.getClass().getMethod("withLogConsumer", Consumer.class);
- 将方法引用显式转换为适当的接口(interface)类型:
withLogConsumer.invoke(object, (Consumer<OutputFrame>) SimpleClass::log);
关于java - 如何通过反射调用方法,并提供方法作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59276729/