GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||
GeezerVison is showing zetcode.com — Java annotations - working with annotations in Java Java annotationslast modified July 4, 2024 In this article we talk about Java annotations. Annotations are a special kind of code element that provides additional information about a program. They are attached to classes, methods, fields, and other program elements using the @ symbol. Annotations themselves don't directly affect how the code runs, but instead provide metadata that can be used by various tools:
The @Override annotation
The @Override does:
Main.java
class User {
private final String firstName;
private final String lastName;
private final String occupation;
public User(String firstName, String lastName, String occupation) {
this.firstName = firstName;
this.lastName = lastName;
this.occupation = occupation;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getOccupation() {
return occupation;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("User{");
sb.append("firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", occupation='").append(occupation).append('\'');
sb.append('}');
return sb.toString();
}
}
void main() {
User[] users = {
new User("John", "Doe", "gardener"),
new User("Roger", "Roe", "driver"),
new User("Paul", "Smith", "teacher"),
};
for (User user : users) {
System.out.println(user);
}
}
In the example, we override the @Deprecated annotation
The
Key features of the
Additional features of the
Main.java
class PassWordGenerator {
@Deprecated
public String generatePassword() {
return "generated password";
}
public String generateSecurePassword() {
return "a secure password";
}
}
// @SuppressWarnings("deprecation")
void main() {
var pgen = new PassWordGenerator();
System.out.println(pgen.generateSecurePassword());
System.out.println(pgen.generatePassword());
}
In the example, we mark the
The Custom annotationWe can create our own annotations in Java. Key elements of a custom Java annotation are summarized in the following table:
The next example creates a custom annotation. com/zetcode/ClassDescription.java
package com.zetcode;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ClassDescription {
String description();
}
We have a com/ztetcode/AnnotationProcessor.java
package com.zetcode;
import java.util.List;
import java.util.Optional;
public class AnnotationProcessor {
public void process(List<Object> objects) {
objects.forEach(obj -> {
Class<?> clazz = obj.getClass();
ClassDescription annotation = clazz.getAnnotation(ClassDescription.class);
// if (annotation != null) {
// System.out.println(annotation.annotationType().getName());
// System.out.println(annotation.description());
// }
Optional.ofNullable(annotation)
.ifPresentOrElse(
ann -> {
System.out.println(ann.annotationType().getName());
System.out.println(ann.description());
},
() -> System.out.println("No annotation found")
);
});
}
}
The com/zetcode/CustomAnnotation.java
package com.zetcode;
import java.util.List;
@ClassDescription(description = "this is a User class")
class User {
}
@ClassDescription(description = "this is a Test class")
class Test {
}
class Hello {
}
public class CustomAnnotation {
private String field;
public static void main(String[] args) {
List<Object> objects = List.of(new User(), new Test(), new Hello());
var processor = new AnnotationProcessor();
processor.process(objects);
}
}
We have two classes that are decorated with SourceIn this article we covered annotations in Java. We have shown how to use existing annotations and how to create custom one. AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Java tutorials. | ||||||||||||
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |