Java
Annotations
Custom annotations and usage.
By EZ4Code Team
annotationannotation
Code
import java.lang.annotation.*;
// Define annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
String value() default "";
int priority() default 0;
}
// Use annotation
class MyClass {
@MyAnnotation(value = "test", priority = 1)
public void doSomething() {}
}
// Read annotation via reflection
for (var method : MyClass.class.getDeclaredMethods()) {
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation ann = method.getAnnotation(MyAnnotation.class);
System.out.println(ann.value() + ":" + ann.priority());
}
}Explanation
Annotations provide metadata for code and can be read at runtime via reflection.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.