Custom Annotation
1. Lead:
Here is an example of how to create custom annotations and get data from annotations.
2. Example:
Authority.java
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target(FIELD)
@Retention(RUNTIME)
@Documented
public @interface Authority {
String role() default "none";
}
AuthorityRange.java
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Retention(RUNTIME)
@Target(FIELD)
public @interface AuthorityRange {
public enum RangeDes{person, team, org};
RangeDes rang() default RangeDes.person;
}
Entity.java
public class Entity {
@Authority(role = "edit")
private String authority;
@AuthorityRange(rang = AuthorityRange.RangeDes.person)
private String range;
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getRange() {
return range;
}
public void setRange(String range) {
this.range = range;
}
}
InfoUtil.java
: Annotation Processor
import java.lang.reflect.Field;
public class InfoUtil {
public static void getInfo(Class<?> clazz){
Field[] fields = clazz.getDeclaredFields();
for(Field field : fields){
if(field.isAnnotationPresent(Authority.class)){
Authority authority = field.getAnnotation(Authority.class);
System.out.println(authority.role());
}
else if(field.isAnnotationPresent(AuthorityRange.class)){
AuthorityRange authorityRange = field.getAnnotation(AuthorityRange.class);
System.out.println(authorityRange.rang().toString());
}
}
}
}
AnnotationApp.java
public class AnnotationApp {
public static void main(String[] args) {
InfoUtil.getInfo(Entity.class);
}
}
3. Attentions
- Ensure that the Jdk version is more than 1.8;
- If you copy the examples directly, needing to add the package.