简体   繁体   English

返回匿名类的新对象的方法

[英]Method that returns new object of anonymous class

Let say that I have interface I1 like this: 假设我有这样的接口I1:

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. 我想创建一个名为MyClass的公共类,它将包含方法getI1 ,该方法将返回实现接口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 您可以使用任何实现I1的类来代替new I1()

here's an example which uses the interface Runnable and the class Thread, which implements Runnable 这是一个使用Runnable接口和Thread类的示例,该类实现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: 对Japu_D_Cret的答案做了一些补充:对于JDK 8,它可能很短:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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