Consider the following contrived "hello, world":
abstract public class Main implements java.util.function.Supplier<Runnable> {
public static void main(String[] args) {
new Main() {
private void hello() {
System.out.println("hello, world");
}
@Override
public Runnable get() {
return this::hello;
}
}.get().run();
}
}
This works. Now, imagine I realize that the hello
method can be made static
, how do I now get the reference to that method? Static method reference require to use the name of the class, which by definition is not there. I tried just trying to refer to hello
or ::hello
or null::hello
but these are not acceptable for the compiler.
Since the method is static, this can of course be easily worked around by putting the static method in the Main
class and referring to it as Main::hello
, but in a more complex setup the advantage of being able to refer to the static method would be restricting the static method to the smallest possible context. A case can be made of course that probably at that point you are probably abusing the ability to have anonymous classes, but my question mostly comes from curiosity to understand whether referring to static methods of anonymous classes is possible at all.
While method references are probably not really possible, another workaround might be to define a lambda and call the static function in it.
abstract public class Main implements java.util.function.Supplier<Runnable> {
public static void main(String[] args) {
new Main() {
private static void hello() {
System.out.println("hello, world");
}
@Override
public Runnable get() {
return () -> hello();
}
}.get().run();
}
}
While I'm not sure whether the compiler can realize that the additional indirection is not necessary, I don't think this would be impossible.