Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it exist annotations for marking a class as singleton or immutable in Java 9?

In most of the programming languages, it is the developer's responsibility to write immutable, singleton classes etc.

However, I feel like this is kind of repeated boilerplate code. More recent programming languages provide better support for achieving this.

Has Java 9 introduced any annotation or similar construct to mark a class as immutable or singleton?

like image 596
JavaUser Avatar asked Apr 30 '18 12:04

JavaUser


2 Answers

No, as far as I know, no such constructs exist in Java 9. Surely that would have been documented in the list of new features.


As a side note, Java EE has the @Singleton annotation, which specifies that a bean is a singleton.


As a further side note there exists an extension to Project Lombok called lombok-pg which has an implementation of a @Singleton annotation:

@Singleton(style=Singleton.Style.HOLDER)
public class SingletonHolderExample {
  private String s;

  public void foo() {
  }
}

This is equivalent to the following code:

public class SingletonHolderExample {

  private static class SingletonHolderExampleHolder {
    private static final SingletonHolderExample INSTANCE = new SingletonHolderExample();
  }

  public static SingletonHolderExample getInstance() {
    return SingletonHolderExampleHolder.INSTANCE;
  }

  private String s;

  public void foo() {
  }
}

Note that Lombok hooks iteslf into the compilation process, and modifies the classes. This is considered by some people as a "hacky" thing to do, and should perhaps be used with causion. Another downside is that you have to modify the IDE in order for it to understand what code Lombok generates. This is done by running the downloaded Lombok jar file.

A good summary of how Lombok works, with its pros and cons, can be found here.

like image 72
Magnilex Avatar answered Nov 01 '22 03:11

Magnilex


In Java EJB you can use @Singleton:

@Singleton
@Startup
public class mySingleton {....}

I Usually use it with @Startup as well.

More on Singleton here

Hope that helps.

like image 24
lucas-ms Avatar answered Nov 01 '22 01:11

lucas-ms