public final class ImageSingletons extends Object
class or interface
, the value is an instance that
extends that class.
When accessing the registry at run time, the key must be a compile time constant. The
ImageSingletons.lookup(java.lang.Class<T>)
is performed during native image generation, and the resulting value is put into
the compiled code as a literal constant. Therefore, the actual map that stores the key-value data
is not necessary at run time, and there is no lookup overhead at run time.
ImageSingletons
avoids static fields: instead of filling a static field during native
image generation and accessing it at run time, the value is put into the ImageSingletons
.
Usually, that happens in one of the early initialization methods of a Feature
.
Modifier and Type | Method and Description |
---|---|
static <T> void |
add(Class<T> key,
T value)
Add a singleton to the registry.
|
static boolean |
contains(Class<?> key)
Checks if a singleton is in the registry.
|
static <T> T |
lookup(Class<T> key)
Lookup a singleton in the registry.
|
public static <T> void add(Class<T> key, T value)
public static <T> T lookup(Class<T> key)
The key must have been added
before, i.e., the result is guaranteed to be non-
null
.
public static boolean contains(Class<?> key)
true
or false
.
The method returns false
since 19.3.0 when not used in the context of a native image.
As such it is safe to write:
if (and let such code run fine in the context ofImageSingletons
.contains(MyService.class)) { MyService myService =ImageSingletons
.lookup(MyService.class); myService.useMyService(); }
native image
as
well as outside of it.