From 599b6aab677439ae1bdea2cdca3233d0b763fd3f Mon Sep 17 00:00:00 2001
From: Reinier Zwitserloot
+
+ You can make a class containing a bunch of
+ For example, if you create
+ All methods that are
+ You can pass any number of classes to the
+ Lombok does not (currently) have any runtime dependencies which means lombok does not (currently) ship with any useful extension methods so you'll have to make your own. However, here's one that might spark your imagination: @ExtensionMethod
was introduced as experimental feature in lombok v0.11.2.
+
+
+ Current status: hold - Currently we feel this feature will not move out of experimental status anytime soon, but it will not significantly change and support for it is unlikely to be removed in future versions of lombok either.
+ @f.experimental>
+
+ <@f.overview>
+ public
, static
methods which all take at least 1 parameter. These methods will extend the type of the first parameter, as if they were instance methods, using the @ExtensionMethod
feature.
+ public static String toTitleCase(String in) { ... }
, you can use the @ExtensionMethod
feature to make it look like the java.lang.String
class has a method named toTitleCase
, which has no arguments. The first argument of the static method fills the role of this
in instance methods.
+ public
, static
, and have at least 1 argument whose type is not primitive, are considered extension methods, and each will be injected into the namespace of the type of the first parameter as if they were instance methods. As in the above example, a call that looks like: foo.toTitleCase()
is replaced with ClassContainingYourExtensionMethod.toTitleCase(foo);
. Note that it is actually not an instant NullPointerException
if foo
is null - it is passed like any other parameter.
+ @ExtensionMethod
annotation; they will all be searched for extension methods. These extension methods apply for any code that is in the annotated class.
+
+ public class ObjectExtensions {
+ public static <T> or(T object, T ifNull) {
+ return object != null ? object : ifNull;
+ }
+}
+ With the above class, if you add @ExtensionMethod(ObjectExtensions.class)
to your class definition, you can write:
+ String x = null;
+System.out.println(x.or("Hello, World!"));
+ The above code will not fail with a NullPointerException
; it will actually output Hello, World!
+
lombok.extensionMethod.flagUsage
= [warning
| error
] (default: not set)
+ @ExtensionMethod
as a warning or error if configured.
+ + Calls are rewritten to a call to the extension method; the static method itself is not inlined. Therefore, the extension method must be present both at compile and at runtime. +
+ Generics is fully applied to figure out extension methods. i.e. if the first parameter of your extension method is List<? extends String>
, then any expression that is compatible with that will have your extension method, but other kinds of lists won't. So, a List<Object>
won't get it, but a List<String>
will.
+