我有一个想通过反射调用的方法:
@Override
public SELF withLogConsumer(Consumer<OutputFrame> consumer) {
this.logConsumers.add(consumer);
return self();
}
在没有反思的情况下,我会使用类似以下内容的方法来调用此方法:
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)
有两个问题,我似乎也找不到答案:
答案 0 :(得分:1)
Method withLogConsumer = object.getClass().getMethod("withLogConsumer", Consumer.class);
withLogConsumer.invoke(object, (Consumer<OutputFrame>) SimpleClass::log);