简体   繁体   中英

Method that returns new object of anonymous class

Let say that I have interface I1 like this:

interface I1 {
   public void setNumber(int num);
}

I want to create let say public class named MyClass that will include method getI1 that will return new object of anonymous class that implements interface I1.

how about this?

public I1 getI1() {
  return new I1() {
    public void setNumber(int num) {
      //do something
    }
  };
}

alternativaly you could use instead of new I1() any class which implements I1

here's an example which uses the interface Runnable and the class Thread, which implements Runnable

public static void main(String[] args) {
  System.out.println("main > start");

  System.out.println("main > r = getRunnable()");
  Runnable r = getRunnable();

  System.out.println("main > r.run()");
  r.run();
  System.out.println("main > Stop");
}

public static Runnable getRunnable() {
  return new Thread() {
    public void run() {
      System.out.println("run > Start");
      //do something
      System.out.println("run > Stop");
    }
  };
}

output is

main > start
main > r = getRunnable()
main > r.run()
run > Start
run > Stop
main > Stop

A little supplement to Japu_D_Cret's answer: for JDK 8, it could be as short as:

public I1 getI1() {
    return num -> {
        // your implementation goes here
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM