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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With