Class AnnotationObject

java.lang.Object
org.apache.juneau.commons.annotation.AnnotationObject
All Implemented Interfaces:
Annotation
Direct Known Subclasses:
AppliedAnnotationObject

public class AnnotationObject extends Object implements Annotation
A concrete implementation of a Java annotation that can be created programmatically at runtime.

This class provides a base for creating annotation instances without requiring them to be declared on program elements at compile-time. It allows annotations to be constructed using a builder pattern and follows all standard Java annotation semantics for equality, hashcode, and string representation.

Overview:

Java annotations are typically declared statically on classes, methods, fields, etc. at compile-time:

@Bean(sort=true) public class MyClass {...}

This class allows you to create those same annotations programmatically:

Bean annotation = BeanAnnotation .create() .sort(true) .build();

Equality and Hashcode:

Follows the standard Java conventions for annotation equality and hashcode calculation as defined in Annotation.equals(Object) and Annotation.hashCode(). This ensures that programmatically-created annotations are equivalent to compile-time declared annotations if they have the same type and properties.

// These two annotations are equal: @Bean(sort=true) class MyClass {} Bean declared = MyClass.class.getAnnotation(Bean.class); Bean programmatic = BeanAnnotation.create().sort(true).build(); assertEquals(declared, programmatic); // true assertEquals(declared.hashCode(), programmatic.hashCode()); // true

Hashcode Caching:

For performance reasons, the hashcode is calculated once and cached on first access. The hash is computed lazily when hashCode() is first called and then stored for subsequent calls.

public MyAnnotation(Builder builder) { super(builder); this.myField = builder.myField; }

Builder Pattern:

Subclasses should provide a nested AnnotationObject.Builder class that extends AnnotationObject.Builder to construct instances using a fluent builder pattern. The builder should:

  • Provide setter methods for each annotation property
  • Return this (or the builder type) from each setter for method chaining
  • Provide a build() method that constructs the final annotation object
Example Implementation:

public class MyAnnotationObject extends AnnotationObject implements MyAnnotation { private final String value; public static class Builder extends AnnotationObject.Builder { String value = ""; public Builder() { super(MyAnnotation.class); } public Builder value(String value) { this.value = value; return this; } public MyAnnotation build() { return new MyAnnotationObject(this); } } public MyAnnotationObject(Builder builder) { super(builder); this.value = builder.value; } @Override public String value() { return value; } }

See Also: