自执行Java方法 [英] Self-executing Java methods

查看:136
本文介绍了自执行Java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,可以编写一个这样的自执行函数:

In JavaScript, it is possible to write a self-executing function like this:

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

我希望用Java做到这一点。例如:

I'm looking to do this in Java. So for example:

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

有这样的事吗?

推荐答案

javascript实际上并没有创建自执行功能。它定义了一个函数,然后立即执行它。

That javascript isn't really creating a "self-executing" function. It's defining a function, and then immediately executing it.

Java不允许您定义独立函数,因此您不能在Java中执行此操作。但是,您可以声明一个匿名类并立即执行其中一个方法:

Java doesn't let you define standalone functions, so you can't do this in 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.)

这篇关于自执行Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆