1
votes

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

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

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");
    }());
}

Is there such a thing?

3
Why do you need a function here ? What's your goal ? Do you know that the scope works very differently in Java and JavaScript ?Denys Séguret
If it makes you happy, it is possible to wrap code in their own blocks { }. So foo: { System.out.println("bar"); } works.Unihedron

3 Answers

6
votes

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. But you could do this in Java 8:

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

which in essence is the same thing @yshavit's answer did in Java 7.

4
votes

That javascript isn't really creating a "self-executing" function. 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. 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.)

0
votes

You can create helper methods (for e.g. run and get) that will execute your custom function.

use run if function doesn't return anything (side effects) and get otherwise

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");

    }

}