Creating custom annotations

前端 未结 1 1147
遇见更好的自我
遇见更好的自我 2021-01-05 12:51

How does annotation work with Java? And how can I create custom annotations like this:

@Entity(keyspace=\':\')
class Student
{
  @Id
  @Attribute(value=\"uid         


        
相关标签:
1条回答
  • 2021-01-05 13:06

    If you create custom annotations you will have to use Reflection API Example Here to process them. You can refere How to declare annotation. Here is how example annotation declaration in java looks like.

    import java.lang.annotation.*;
    
    /**
     * Indicates that the annotated method is a test method.
     * This annotation should be used only on parameterless static methods.
    */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Test { }
    

    Retention and Target are known as meta-annotations.

    RetentionPolicy.RUNTIME indicates that you want to retain the annotation at runtime and you can access it at runtime.

    ElementType.METHOD indicates that you can declare annotation only on methods similarly you can configure your annotation for class level, member variable level etc.

    Each Reflection class has methods to get annotations which are declared.

    public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
    Returns this element's annotation for the specified type if such an annotation is present, else null.
    
    public Annotation[] getDeclaredAnnotations()
    Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers. 
    

    You will find these methods present for Field, Method,Class classes.

    e.g.To retrieve annotations present on specified class at run time

     Annotation[] annos = ob.getClass().getAnnotations();
    
    0 讨论(0)
提交回复
热议问题