Practical utility annotations for common programming tasks including null checking, exception handling, and synchronization.
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface NonNull {
}@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.SOURCE)
public @interface SneakyThrows {
Class<? extends Throwable>[] value() default java.lang.Throwable.class;
}@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Synchronized {
String value() default "";
}@Target(ElementType.LOCAL_VARIABLE)
@Retention(RetentionPolicy.SOURCE)
public @interface Cleanup {
String value() default "close";
}Guards all statements in a method with a java.util.concurrent.locks.Lock for thread safety.
/**
* Guards all statements in an annotation method with a Lock.
*
* For non-static methods, a field named $lock is used, and for static methods,
* $LOCK is used. These will be generated if needed and if they aren't already present.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Locked {
/**
* Optional: specify the name of a different field to lock on. It is a compile time error if this field
* doesn't already exist (the fields are automatically generated only if you don't specify a specific name).
*
* @return Name of the field to lock on (blank = generate one).
*/
String value() default "";
/**
* Locks using a ReadWriteLock#readLock().
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Read {
String value() default "";
}
/**
* Locks using a ReadWriteLock#writeLock().
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Write {
String value() default "";
}
}Usage Examples:
import lombok.*;
import java.nio.file.*;
import java.io.*;
public class FileProcessor {
@SneakyThrows
public String readFile(String filename) {
return Files.readString(Paths.get(filename));
}
@Synchronized
public void processData(@NonNull String data) {
// Thread-safe processing using synchronized block
}
@Locked
public void updateCounter() {
// Thread-safe using java.util.concurrent.locks.Lock
counter++;
}
@Locked.Read
public int readCounter() {
// Thread-safe read using ReadWriteLock.readLock()
return counter;
}
@Locked.Write
public void resetCounter() {
// Thread-safe write using ReadWriteLock.writeLock()
counter = 0;
}
@SneakyThrows
public void processFile(String filename) {
@Cleanup FileInputStream fis = new FileInputStream(filename);
// File will be automatically closed
// Process file content...
}
}