mardi 10 décembre 2019

How to call a method via reflection, and provide a method as param

I have a method that I want to call via reflection:

    @Override
    public SELF withLogConsumer(Consumer<OutputFrame> consumer) {
        this.logConsumers.add(consumer);
        return self();
    }

Without reflection I would call this method using something like:

   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);
    }

Using reflection I would expect to be able to do:

      Constructor<?> ctor = SimpleClass.class.getConstructor();
      Object object = ctor.newInstance();
      Method withLogConsumer = object.getClass().getMethod("withLogConsumer", Consumer<OutputFrame>.class);
      withLogConsumer.invoke(object, SimpleClass::log)

There are two problems with this that I cannot seem to find the answers too:

  1. How do I create a method using reflection that accepts a generic method parameter type? (Like if my method accepted ArrayList)
  2. How do I then pass in a method using double colon syntax?




Aucun commentaire:

Enregistrer un commentaire