Java 8 - how to access object and method encapsulated as lambda

In Java, you can “capture” a method call on an object as Runnable, as shown in the example.

Later, having access to this Runnable instance, is it possible to actually access the “captured” object and method parameters of the method that is called (if possible, this probably needs to be done using reflection).

For instance:

class SomePrintingClass {
  public void print(String myText) {
    System.out.println(myText);

  }
}


public class HowToAccess {
  public static void main(String[] args) throws Exception {
    final String myText = "How to access this?";

    final SomePrintingClass printer = new SomePrintingClass();

    Runnable r = () -> printer.print(myText); // capture as Runnable

    inspect(r);
  }


  private static void inspect(Runnable runnable) {
    // I have reference only to runnable... can I access "printer" here

  }


}

Is it possible in the "verification" method to access (possibly through reflection) "printer" and "myText", which was passed as a parameter?

+6
source share
3 answers

, runnable ( ). .

, , myText final, ( ):

private static void inspect(Runnable runnable) throws Exception {       
    for(Field f : runnable.getClass().getDeclaredFields()) {
        f.setAccessible(true);
        System.out.println("name: " + f.getName());
        Object o = f.get(runnable);
        System.out.println("value: " + o);
        System.out.println("class: " + o.getClass());
        System.out.println();
    }
}

name: arg$1
value: test.SomePrintingClass@1fb3ebeb
class: class test.SomePrintingClass

name: arg$2
value: How to access this?
class: class java.lang.String
+8

. AOP .

0

, - , runnable Thread .

    class SomePrintingClass {
          public void print(String myText) {
            System.out.println(myText);

          }
        }


        public class HowToAccess {
          public static void main(String[] args) throws Exception {
            final String myText = "How to access this?";

            final SomePrintingClass printer = new SomePrintingClass();

            Runnable r = () -> printer.print(myText); // capture as Runnable

            inspect(r);
          }


          private static void inspect(Runnable runnable) {
            Thread t = new Thread(runnable);
            t.start();

          }


        }

:

?

-2

Source: https://habr.com/ru/post/1670067/


All Articles