### Vanilla Java Logging Examples Source: https://projectlombok.org/features/log Demonstrates how to declare loggers using standard Java logging, SLF4J, and Apache Commons Logging. ```java public class LogExample { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName()); public static void main(String... args) { log.severe("Something's wrong here"); } } ``` ```java public class LogExampleOther { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class); public static void main(String... args) { log.error("Something else is wrong here"); } } ``` ```java public class LogExampleCategory { private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog"); public static void main(String... args) { log.error("Calling the 'CounterLog' with a message"); } } ``` -------------------------------- ### Hierarchical Configuration Example Source: https://projectlombok.org/features/configuration Demonstrates how configuration settings are applied hierarchically. Settings in a subdirectory's `lombok.config` file override those in a parent directory. ```properties # In /Users/me/projects/lombok.config lombok.log.fieldName = foobar ``` ```properties # In /Users/me/projects/MyProject/lombok.config lombok.log.fieldName = xyzzy ``` -------------------------------- ### Basic Delegation Example in Java Source: https://projectlombok.org/features/experimental/Delegate This example demonstrates how to use delegation in Java. The DelegationExample class implements a SimpleCollection interface and delegates its add and remove methods to an internal ArrayList. This pattern is useful for forwarding method calls to another object. ```java import java.util.ArrayList; import java.util.Collection; public class DelegationExample { private interface SimpleCollection { boolean add(String item); boolean remove(Object item); } private final Collection collection = new ArrayList(); @java.lang.SuppressWarnings("all") public boolean add(final String item) { return this.collection.add(item); } @java.lang.SuppressWarnings("all") public boolean remove(final Object item) { return this.collection.remove(item); } } ``` -------------------------------- ### Import Configuration from Absolute Paths Source: https://projectlombok.org/features/configuration Import configuration settings from files using absolute paths. This is more common for individual setups than shared projects. ```properties # Linux import /etc/lombok/model.config ``` ```properties # Windows import d:/lombok/model.config ``` -------------------------------- ### Vanilla Java Accessors Example Source: https://projectlombok.org/features/experimental/Accessors Demonstrates manual implementation of getter and setter methods for a field in Java. This serves as a baseline for understanding Lombok's automated generation. ```java public class AccessorsExample { private int age = 10; public int age() { return this.age; } public AccessorsExample age(final int age) { this.age = age; return this; } } class PrefixExample { private String fName = "Hello, World!"; public String getName() { return this.fName; } } ``` -------------------------------- ### Vanilla Java Getters and Setters Source: https://projectlombok.org/features/GetterSetter This example shows the equivalent Java code without Lombok, demonstrating the boilerplate required for manual getter and setter generation. ```java public class GetterSetterExample { /** * Age of the person. Water is wet. */ private int age = 10; /** * Name of the person. */ private String name; @Override public String toString() { return String.format("%s (age: %d)", name, age); } /** * Age of the person. Water is wet. * * @return The current value of this person's age. Circles are round. */ public int getAge() { return age; } /** * Age of the person. Water is wet. * * @param age New value for this person's age. Sky is blue. */ public void setAge(int age) { this.age = age; } /** * Changes the name of this person. * * @param name The new value. */ protected void setName(String name) { this.name = name; } } ``` -------------------------------- ### Manual Resource Management in Vanilla Java Source: https://projectlombok.org/features/Cleanup This example demonstrates the equivalent resource management in plain Java using nested try-finally blocks, highlighting the verbosity that @Cleanup aims to reduce. ```java import java.io.*; public class CleanupExample { public static void main(String[] args) throws IOException { InputStream in = new FileInputStream(args[0]); try { OutputStream out = new FileOutputStream(args[1]); try { byte[] b = new byte[10000]; while (true) { int r = in.read(b); if (r == -1) break; out.write(b, 0, r); } } finally { if (out != null) { out.close(); } } } finally { if (in != null) { in.close(); } } } } ``` -------------------------------- ### Lombok Builder Example Source: https://projectlombok.org/features/Builder A basic example of using Lombok's @Builder and @Singular annotations to automatically generate a builder pattern for a class. Includes a default value for a field. ```java import lombok.Builder; import lombok.Singular; import java.util.Set; @Builder public class BuilderExample { @Builder.Default private long created = System.currentTimeMillis(); private String name; private int age; @Singular private Set occupations; } ``` -------------------------------- ### Vanilla Java Equivalent for Locked Example Source: https://projectlombok.org/features/Locked Provides the equivalent Java code without Lombok, illustrating the manual implementation of ReentrantLock and ReentrantReadWriteLock for thread safety. ```java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class LockedExample { private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock baseLock = new ReentrantLock(); private int value = 0; public int getValue() { this.lock.readLock().lock(); try { return value; } finally { this.lock.readLock().unlock(); } } public void setValue(int newValue) { this.lock.writeLock().lock(); try { value = newValue; } finally { this.lock.writeLock().unlock(); } } public void foo() { this.baseLock.lock(); try { System.out.println("bar"); } finally { this.baseLock.unlock(); } } } ``` -------------------------------- ### Vanilla Java Utility Class Example Source: https://projectlombok.org/features/experimental/UtilityClass Shows the equivalent implementation of a utility class in vanilla Java without using Lombok. This includes a private constructor, static members, and a final class. ```java public final class UtilityClassExample { private static final int CONSTANT = 5; private UtilityClassExample() { throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } public static int addSomething(int in) { return in + CONSTANT; } } ``` -------------------------------- ### Lombok @UtilityClass Example Source: https://projectlombok.org/features/experimental/UtilityClass Demonstrates how to use the @UtilityClass annotation to create a utility class with Lombok. This automatically generates a private constructor and marks all members as static. ```java import lombok.experimental.UtilityClass; @UtilityClass public class UtilityClassExample { private final int CONSTANT = 5; public int addSomething(int in) { return in + CONSTANT; } } ``` -------------------------------- ### Equivalent Vanilla Java code for val examples Source: https://projectlombok.org/features/val Shows the equivalent code in standard Java without Lombok's `val` feature, explicitly declaring types and the `final` keyword. ```java import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class ValExample { public String example() { final ArrayList example = new ArrayList(); example.add("Hello, World!"); final String foo = example.get(0); return foo.toLowerCase(); } public void example2() { final HashMap map = new HashMap(); map.put(0, "zero"); map.put(5, "five"); for (final Map.Entry entry : map.entrySet()) { System.out.printf("%d: %s\n", entry.getKey(), entry.getValue()); } } } ``` -------------------------------- ### Lombok @With Example Source: https://projectlombok.org/features/With Demonstrates the usage of @With annotation for generating protected and public with methods. Requires an all-arguments constructor, which can be provided by Lombok's @AllArgsConstructor or @Value, or written manually. ```java import lombok.AccessLevel; import lombok.NonNull; import lombok.With; public class WithExample { @With(AccessLevel.PROTECTED) @NonNull private final String name; @With private final int age; public WithExample(@NonNull String name, int age) { this.name = name; this.age = age; } } ``` -------------------------------- ### Lombok onX Example Source: https://projectlombok.org/features/experimental/onX Demonstrates the usage of onX annotations with @AllArgsConstructor, @Getter, and @Setter to apply custom annotations like @Inject, @Id, @Column, and @Max to generated code. ```java import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import javax.inject.Inject; import javax.persistence.Id; import javax.persistence.Column; import javax.validation.constraints.Max; @AllArgsConstructor(onConstructor_=@Inject) public class OnXExample { @Getter(onMethod_={@Id, @Column(name="unique-id")}) @Setter(onParam_=@Max(10000)) private long unid; } ``` -------------------------------- ### Using onMethod for Annotations (JDK 7 and earlier) Source: https://projectlombok.org/api/lombok/experimental/Wither This example shows how to use the deprecated 'onMethod' element to apply annotations to the generated wither method, using the syntax for JDK 7 and earlier. ```java @Wither(onMethod=@__({@AnnotationsGoHere})) ``` -------------------------------- ### Method with @NonNull Parameter (Vanilla Java) Source: https://projectlombok.org/features/NonNull This is the equivalent of the Lombok example, showing the manually written null-check for a constructor parameter. Use this if you are not using Lombok or prefer explicit null-checks. ```java import lombok.NonNull; public class NonNullExample extends Something { private String name; public NonNullExample(@NonNull Person person) { super("Hello"); if (person == null) { throw new NullPointerException("person is marked non-null but is null"); } this.name = person.getName(); } } ``` -------------------------------- ### Using onMethod_ for Annotations (JDK 8+) Source: https://projectlombok.org/api/lombok/experimental/Wither This example demonstrates the use of the deprecated 'onMethod_' element for applying annotations to the generated wither method, compatible with JDK 8 and later. ```java @Wither(onMethod_={@AnnotationsGohere}) ``` -------------------------------- ### Using onParam for Annotations (JDK 7 and earlier) Source: https://projectlombok.org/api/lombok/experimental/Wither This example illustrates the deprecated 'onParam' element for applying annotations to the parameter of the generated wither method, using the syntax for JDK 7 and earlier. ```java @Wither(onParam=@__({@AnnotationsGoHere})) ``` -------------------------------- ### Generated Wither Method Example Source: https://projectlombok.org/api/lombok/experimental/Wither This is an example of the 'wither' method automatically generated by Lombok for a field annotated with @Wither. It demonstrates how a new instance is created with a modified field value. ```java public SELF_TYPE withFoo(int foo) { return this.foo == foo ? this : new SELF_TYPE(otherField1, otherField2, foo); } ``` -------------------------------- ### Import Configuration using Environment Variables Source: https://projectlombok.org/features/configuration Import configuration files by referencing environment variables. Tilde (~) is also supported for user home directory expansion. ```properties # Environment variables are names surrounded by angle brackets (<, >). # They are replaced by System.getenv(name), if present. import /shared.config ``` ```properties # A tilde (~) at the start gets replaced by System.getProperty("user.home", "~"). import ~/my.config ``` -------------------------------- ### Lombok @Locked Example with Read/Write and Custom Lock Source: https://projectlombok.org/features/Locked Demonstrates the usage of @Locked.Read, @Locked.Write, and a custom lock field named 'baseLock'. This example shows how Lombok simplifies thread-safe access to shared resources. ```java import lombok.Locked; public class LockedExample { private int value = 0; @Locked.Read public int getValue() { return value; } @Locked.Write public void setValue(int newValue) { value = newValue; } @Locked("baseLock") public void foo() { System.out.println("bar"); } } ``` -------------------------------- ### Maven POM Configuration for ECJ and Lombok Source: https://projectlombok.org/setup/ecj This minimal example shows how to configure the maven-compiler-plugin in your pom.xml to use ECJ and include Lombok as a dependency. ```xml 4.0.0 org.projectlombok eclipse-compiler-test 1.0-SNAPSHOT UTF-8 1.18.46 org.projectlombok lombok ${lombok.version} provided maven-compiler-plugin 3.10.1 eclipse org.codehaus.plexus plexus-compiler-eclipse 2.11.1 org.projectlombok lombok ${lombok.version} ``` -------------------------------- ### Vanilla Java Equivalent Source: https://projectlombok.org/features/experimental/onX Shows the equivalent Java code without Lombok, manually implementing the constructor, getter, and setter with the same annotations. ```java import javax.inject.Inject; import javax.persistence.Id; import javax.persistence.Column; import javax.validation.constraints.Max; public class OnXExample { private long unid; @Inject public OnXExample(long unid) { this.unid = unid; } @Id @Column(name="unique-id") public long getUnid() { return unid; } public void setUnid(@Max(10000) long unid) { this.unid = unid; } } ``` -------------------------------- ### Generate toString() with Lombok Source: https://projectlombok.org/features/ToString Annotate your class with @ToString to automatically generate a toString() method. This example demonstrates basic usage and exclusion of a field. ```java import lombok.ToString; @ToString public class ToStringExample { private static final int STATIC_VAR = 10; private String name; private Shape shape = new Square(5, 10); private String[] tags; @ToString.Exclude private int id; public String getName() { return this.name; } @ToString(callSuper=true, includeFieldNames=true) public static class Square extends Shape { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } } } ``` -------------------------------- ### Set Lombok Accessors Fluent Source: https://projectlombok.org/features/configuration Configure generated setters and getters to use field names directly, without `get` or `set` prefixes. ```properties lombok.accessors.fluent = true ``` -------------------------------- ### Import Configuration from Relative Path Source: https://projectlombok.org/features/configuration Import configuration settings from another file using a relative path. The path is resolved relative to the importing file. ```properties import ../configuration/model.config ``` -------------------------------- ### Example Extension Method Class Source: https://projectlombok.org/features/experimental/ExtensionMethod Define static methods that can be used as extension methods. The first parameter of the static method determines the type it extends. ```java public class ObjectExtensions { public static T or(T object, T ifNull) { return object != null ? object : ifNull; } } ``` -------------------------------- ### Specifying Access Level for Wither Method Source: https://projectlombok.org/api/lombok/experimental/Wither This example demonstrates how to use the deprecated 'value' element to specify a non-public access level for the generated wither method. ```java @Wither(value = AccessLevel.PROTECTED) ``` -------------------------------- ### Vanilla Java Equivalent of @With Source: https://projectlombok.org/features/With Shows the equivalent Java code without Lombok annotations, illustrating the manual implementation of 'with' methods for immutability. ```java import lombok.NonNull; public class WithExample { private @NonNull final String name; private final int age; public WithExample(String name, int age) { if (name == null) throw new NullPointerException(); this.name = name; this.age = age; } protected WithExample withName(@NonNull String name) { if (name == null) throw new java.lang.NullPointerException("name"); return this.name == name ? this : new WithExample(name, age); } public WithExample withAge(int age) { return this.age == age ? this : new WithExample(name, age); } } ``` -------------------------------- ### Create Lightweight Lombok API Jar for Eclipse Source: https://projectlombok.org/setup/android Run this command to create a `lombok-api.jar` containing only annotations, which is useful for Android projects in Eclipse. ```bash java -jar lombok.jar publicApi ``` -------------------------------- ### SingularExample Builder Implementation Source: https://projectlombok.org/features/BuilderSingular This code implements the build method for the SingularExample, handling different collection types like sets, lists, and maps, ensuring immutability where appropriate. It uses switch statements to efficiently manage empty, single-element, and default collection cases. ```java java.util.Set occupations; **switch** (**this**.occupations == **null** ? 0 : **this**.occupations.size()) { **case** 0: occupations = java.util.Collections.emptySet(); **break**; **case** 1: occupations = java.util.Collections.singleton(**this**.occupations.get(0)); **break**; **default**: occupations = **new** java.util.LinkedHashSet(**this**.occupations.size() < 1073741824 ? 1 + **this**.occupations.size() + (**this**.occupations.size() - 3) / 3 : java.lang.Integer.MAX_VALUE); occupations.addAll(**this**.occupations); occupations = java.util.Collections.unmodifiableSet(occupations); } com.google.common.collect.ImmutableList axes = **this**.axes == **null** ? com.google.common.collect.ImmutableList.of() : **this**.axes.build(); java.util.SortedMap elves = **new** java.util.TreeMap(); **if** (**this**.elves$key != **null**) **for** (**int** **$i** = 0; $i < (**this**.elves$key == **null** ? 0 : **this**.elves$key.size()); $i++) elves.put(**this**.elves$key.get($i), **this**.elves$value.get($i)); elves = java.util.Collections.unmodifiableSortedMap(elves); java.util.Collection minutiae; **switch** (**this**.minutiae == **null** ? 0 : **this**.minutiae.size()) { **case** 0: minutiae = java.util.Collections.emptyList(); **break**; **case** 1: minutiae = java.util.Collections.singletonList(**this**.minutiae.get(0)); **break**; **default**: minutiae = java.util.Collections.unmodifiableList(**new** java.util.ArrayList(**this**.minutiae)); } **return** **new** SingularExample(occupations, axes, elves, minutiae); } ``` -------------------------------- ### Using @ExtensionMethod in a Class Source: https://projectlombok.org/features/experimental/ExtensionMethod Annotate a class with @ExtensionMethod to enable extension methods from specified classes. This example shows how to use the 'or' and 'toTitleCase' extension methods. ```java import lombok.experimental.ExtensionMethod; @ExtensionMethod({java.util.Arrays.class, Extensions.class}) public class ExtensionMethodExample { public String test() { int[] intArray = {5, 3, 8, 2}; intArray.sort(); String iAmNull = null; return iAmNull.or("hELlO, WORlD!".toTitleCase()); } } class Extensions { public static T or(T obj, T ifNull) { return obj != null ? obj : ifNull; } public static String toTitleCase(String in) { if (in.isEmpty()) return in; return "" + Character.toTitleCase(in.charAt(0)) + in.substring(1).toLowerCase(); } } ``` -------------------------------- ### Vanilla Java Builder Implementation Source: https://projectlombok.org/features/Builder A manual implementation of the builder pattern in vanilla Java, demonstrating the equivalent functionality to Lombok's @Builder. This includes constructor, builder class, and methods for setting fields. ```java import java.util.Set; public class BuilderExample { private long created; private String name; private int age; private Set occupations; BuilderExample(String name, int age, Set occupations) { this.name = name; this.age = age; this.occupations = occupations; } private static long $default$created() { return System.currentTimeMillis(); } public static BuilderExampleBuilder builder() { return new BuilderExampleBuilder(); } public static class BuilderExampleBuilder { private long created; private boolean created$set; private String name; private int age; private java.util.ArrayList occupations; BuilderExampleBuilder() { } public BuilderExampleBuilder created(long created) { this.created = created; this.created$set = true; return this; } public BuilderExampleBuilder name(String name) { this.name = name; return this; } public BuilderExampleBuilder age(int age) { this.age = age; return this; } public BuilderExampleBuilder occupation(String occupation) { if (this.occupations == null) { this.occupations = new java.util.ArrayList(); } this.occupations.add(occupation); return this; } public BuilderExampleBuilder occupations(Collection occupations) { if (this.occupations == null) { this.occupations = new java.util.ArrayList(); } this.occupations.addAll(occupations); return this; } public BuilderExampleBuilder clearOccupations() { if (this.occupations != null) { this.occupations.clear(); } return this; } public BuilderExample build() { // complicated switch statement to produce a compact properly sized immutable set omitted. Set occupations = ...; return new BuilderExample(created$set ? created : BuilderExample.$default$created(), name, age, occupations); } @java.lang.Override public String toString() { return "BuilderExample.BuilderExampleBuilder(created = " + this.created + ", name = " + this.name + ", age = " + this.age + ", occupations = " + this.occupations + ")"; } } } ``` -------------------------------- ### Import Configuration from Archives Source: https://projectlombok.org/features/configuration Import configuration files located within JAR or ZIP archives. Specify the archive path and optionally the path to the config file within the archive. ```properties # Use 'lombok.config' from the root of the archive. import ../deps/lombok-config.jar ``` ```properties # Use a given file in the archive. import ../deps/lombok-config.zip!base/model.config ``` -------------------------------- ### Equivalent Vanilla Java Code Source: https://projectlombok.org/features/experimental/ExtensionMethod This demonstrates the equivalent functionality without using Lombok's @ExtensionMethod, showing the explicit static method calls. ```java public class ExtensionMethodExample { public String test() { int[] intArray = {5, 3, 8, 2}; java.util.Arrays.sort(intArray); String iAmNull = null; return Extensions.or(iAmNull, Extensions.toTitleCase("hELlO, WORlD!")); } } class Extensions { public static T or(T obj, T ifNull) { return obj != null ? obj : ifNull; } public static String toTitleCase(String in) { if (in.isEmpty()) return in; return "" + Character.toTitleCase(in.charAt(0)) + in.substring(1).toLowerCase(); } } ``` -------------------------------- ### Using @FieldDefaults for Default Modifiers Source: https://projectlombok.org/features/experimental/FieldDefaults This example demonstrates how to use @FieldDefaults to make all fields private and final by default. Fields can be exempted using @NonFinal or @PackagePrivate annotations. ```java import lombok.AccessLevel; import lombok.experimental.FieldDefaults; import lombok.experimental.NonFinal; import lombok.experimental.PackagePrivate; @FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE) public class FieldDefaultsExample { public final int a; int b; @NonFinal int c; @PackagePrivate int d; FieldDefaultsExample() { a = 0; b = 0; d = 0; } } ``` -------------------------------- ### Static Builder Factory Method Source: https://projectlombok.org/features/builderSingular Provides a static factory method to create a new instance of the SingularExampleBuilder. This is the entry point for building a SingularExample object. ```java @java.lang.SuppressWarnings("all") **public** **static** SingularExampleBuilder builder() { **return** **new** SingularExampleBuilder(); } ``` -------------------------------- ### Delegate Public Methods with Types Source: https://projectlombok.org/features/experimental/Delegate Use @Delegate with the 'types' parameter to delegate specific public methods from a collection to an ArrayList. This example delegates methods defined in SimpleCollection. ```java import java.util.ArrayList; import java.util.Collection; import lombok.experimental.Delegate; public class DelegationExample { private interface SimpleCollection { boolean add(String item); boolean remove(Object item); } @Delegate(types=SimpleCollection.class) private final Collection collection = new ArrayList(); } ``` -------------------------------- ### Add Lombok to Bootclasspath (Older Versions) Source: https://projectlombok.org/setup/ecj Add this VM argument if you are using an older version of Lombok or Java to ensure compatibility. ```bash **-Xbootclasspath/p:lombok.jar** ``` -------------------------------- ### Vanilla Java Equivalent without @Helper Source: https://projectlombok.org/features/experimental/Helper Shows the equivalent implementation in standard Java without using Lombok's @Helper annotation. This requires explicit instantiation of the helper class and prefixing method calls with the instance variable. ```java public class HelperExample { int someMethod(int arg1) { int localVar = 5; class Helpers { int helperMethod(int arg) { return arg + localVar; } } Helpers $Helpers = new Helpers(); return $Helpers.helperMethod(10); } } ``` -------------------------------- ### Using onParam_ for Annotations (JDK 8+) Source: https://projectlombok.org/api/lombok/experimental/Wither This example shows the deprecated 'onParam_' element for applying annotations to the parameter of the generated wither method, compatible with JDK 8 and later. ```java @Wither(onParam_={@AnnotationsGohere}) ``` -------------------------------- ### SingularExample Static Builder Method Source: https://projectlombok.org/features/BuilderSingular A static factory method to create a new instance of the SingularExampleBuilder, allowing for generic type specification. ```java @java.lang.SuppressWarnings("all") public static SingularExampleBuilder builder() { return new SingularExampleBuilder(); } ```