如何通过反射调用方法,并提供方法作为参数

KyleAure:

我有一个要通过反射调用的方法:

    @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)

这有两个问题,我似乎也找不到答案:

  1. 如何使用接受通用方法参数类型的反射创建方法?(就像我的方法接受ArrayList一样)
  2. 然后如何使用双冒号语法传递方法?
路易斯·瓦瑟曼:
  1. 忽略泛型类型;使用原始的,擦除的非通用类型。Method withLogConsumer = object.getClass().getMethod("withLogConsumer", Consumer.class);
  2. 将方法引用显式转换为适当的接口类型: withLogConsumer.invoke(object, (Consumer<OutputFrame>) SimpleClass::log);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章