简体   繁体   English

自执行 Java 方法

[英]Self-executing Java methods

In JavaScript, it is possible to write a self-executing function like this:在 JavaScript 中,可以编写这样的自执行函数:

(function foo() {
    console.log("bar");
}());

I'm looking to do this in Java.我希望在 Java 中做到这一点。 So for example:例如:

// This code does not work obviously
public static void main(String[] args) {
    (foo() {
        System.out.println("bar");
    }());
}

Is there such a thing?有这样的事情吗?

As others have said, there's not much reason to do this in Java, since the reasons for doing it in JavaScript aren't problems in Java.正如其他人所说,在 Java 中没有太多理由这样做,因为在 JavaScript 中这样做的原因不是 Java 中的问题。 But you could do this in Java 8:但是你可以在 Java 8 中做到这一点:

((Runnable)(() -> System.out.println("Hello, world"))).run();

which in essence is the same thing @yshavit's answer did in Java 7.这本质上与@yshavit 的回答在 Java 7 中所做的相同。

That javascript isn't really creating a "self-executing" function.那个 javascript 并没有真正创建一个“自执行”函数。 It's defining a function, and then immediately executing it.它定义了一个函数,然后立即执行它。

Java doesn't let you define standalone functions, so you can't do this in Java. Java 不允许您定义独立函数,因此您不能在 Java 中执行此操作。 You can however declare an anonymous class and immediately execute one of its methods:但是,您可以声明一个匿名类并立即执行其方法之一:

new Runnable() {
  @Override
  public void run() {
    System.out.println("hello");
  }
}.run();

This is sometimes done with new threads.这有时是通过新线程完成的。 Something like:就像是:

new Thread(new Runnable() {
    // override Runnable.run
}).start();

(Though in a lot of cases, you'll want to do better thread management -- submit the runnable to an executor service, for instance.) (尽管在很多情况下,您会希望进行更好的线程管理——例如,将可运行文件提交给执行程序服务。)

You can create helper methods (for eg run and get ) that will execute your custom function.您可以创建将执行您的自定义函数的辅助方法(例如runget )。

use run if function doesn't return anything (side effects) and get otherwise使用run ,如果功能不返回任何东西(副作用),并get否则

import java.util.function.Supplier;

public interface MyApp {

    static void run(Runnable supp) {
        supp.run();
    }

    static <R> R get(Supplier<R> supp) {
        return supp.get();
    }

    static void test() {

        run(() -> System.out.println("bar"));
        var v = get(() -> "Hello");

    }

}

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

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