我有一个要通过反射调用的方法:
@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)
这有两个问题,我似乎也找不到答案:
Method withLogConsumer = object.getClass().getMethod("withLogConsumer", Consumer.class);
withLogConsumer.invoke(object, (Consumer<OutputFrame>) SimpleClass::log);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句