[go: nahoru, domu]

Jump to content

Java annotation: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
m spaces
 
(One intermediate revision by one other user not shown)
Line 1: Line 1:
{{Short description|Syntactic metadata for Java source code}}
{{Short description|Syntactic metadata for Java source code}}
In the [[Java (programming language)|Java computer programming language]], an '''annotation''' is a form of syntactic [[metadata]] that can be added to Java [[source code]].<ref>{{cite web|url = http://download.oracle.com/javase/1,5.0/docs/guide/language/annotations.html|title = Annotations|access-date = 2011-09-30|publisher = [[Sun Microsystems]]|archive-url = https://web.archive.org/web/20110925021948/http://download.oracle.com/javase/1,5.0/docs/guide/language/annotations.html|archive-date = 2011-09-25|url-status = dead}}.</ref> [[Class (computer programming)|Classes]], [[Method (computer programming)|methods]], [[Variable (computer science)|variables]], [[Parameter (computer programming)|parameters]] and [[Java package]]s may be annotated. Like [[Javadoc]] tags, Java annotations can be read from source files. Unlike [[Javadoc]] tags, Java annotations can also be embedded in and read from [[Java class file]]s generated by the [[Java compiler]]. This allows annotations to be retained by the [[Java virtual machine]] at [[Run time (program lifecycle phase)|run-time]] and read via [[reflection (computer science)|reflection]].<ref>{{Cite book|title = Java(TM) Language Specification|edition = 3rd|publisher = [[Prentice Hall]]|year = 2005|isbn = 0-321-24678-0|url = http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html|author = Sun Microsystems|author-link = Sun Microsystems}}.</ref> It is possible to create meta-annotations out of the existing ones in Java.<ref>{{cite web
In the [[Java (programming language)|Java computer programming language]], an '''annotation''' is a form of syntactic [[metadata]] that can be added to Java [[source code]].<ref>{{cite web|url = http://download.oracle.com/javase/1,5.0/docs/guide/language/annotations.html|title = Annotations|access-date = 2011-09-30|publisher = [[Sun Microsystems]]|archive-url = https://web.archive.org/web/20110925021948/http://download.oracle.com/javase/1,5.0/docs/guide/language/annotations.html|archive-date = 2011-09-25|url-status = dead}}.</ref> [[Class (computer programming)|Classes]], [[Method (computer programming)|methods]], [[Variable (computer science)|variables]], [[Parameter (computer programming)|parameters]] and [[Java package]]s may be annotated. Like [[Javadoc]] tags, Java annotations can be read from source files. Unlike [[Javadoc]] tags, Java annotations can also be embedded in and read from [[Java class file]]s generated by the [[Java compiler]]. This allows annotations to be retained by the [[Java virtual machine]] at [[Run time (program lifecycle phase)|run-time]] and read via [[reflection (computer science)|reflection]].<ref>{{Cite book|title = Java(TM) Language Specification|edition = 3rd|publisher = [[Prentice Hall]]|year = 2005|isbn = 0-321-24678-0|url = http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html|author = Sun Microsystems|author-link = Sun Microsystems}}.</ref> It is possible to create meta-annotations out of the existing ones in Java.<ref>{{cite web
|url=http://www.25hoursaday.com/
|url=http://www.25hoursaday.com/
|title=A COMPARISON OF MICROSOFT'S C# PROGRAMMING LANGUAGE TO SUN MICROSYSTEMS' JAVA PROGRAMMING LANGUAGE: Metadata Annotations
|title=A COMPARISON OF MICROSOFT'S C# PROGRAMMING LANGUAGE TO SUN MICROSYSTEMS' JAVA PROGRAMMING LANGUAGE: Metadata Annotations
|author=Dare Obasanjo
|author=Dare Obasanjo
|year=2007
|year=2007
|publisher=Dare Obasanjo
|publisher=Dare Obasanjo
|archive-url=https://web.archive.org/web/20120919093308/http://25hoursaday.com/
|archive-url=https://web.archive.org/web/20120919093308/http://25hoursaday.com/
|archive-date=2012-09-19
|archive-date=2012-09-19
|access-date=2012-09-20
|access-date=2012-09-20
|url-status=dead
|url-status=dead
}}</ref>
}}</ref>


== History ==
== History ==
The [[Java (software platform)|Java platform]] has various ''ad-hoc'' annotation mechanisms—for example, the ''<code>transient</code>'' modifier, or the ''<code>@Deprecated</code>'' javadoc tag. The [[Java Specification Request]] JSR-175 introduced the general-purpose annotation (also known as ''metadata'') facility to the [[Java Community Process]] in 2002; it gained approval in September 2004.<ref>
The [[Java (software platform)|Java platform]] has various ''ad-hoc'' annotation mechanisms—for example, the ''<code>transient</code>'' modifier, or the ''<code>@Deprecated</code>'' javadoc tag. The [[Java Specification Request]] JSR-175 introduced the general-purpose annotation (also known as ''metadata'') facility to the [[Java Community Process]] in 2002; it gained approval in September 2004.<ref>{{cite web
{{cite web|url = http://www.jcp.org/en/jsr/detail?id=175#2
|url = http://www.jcp.org/en/jsr/detail?id=175#2
|title = JSR 175: A Metadata Facility for the JavaTM Programming Language|date = 2006-11-02
|title = JSR 175: A Metadata Facility for the JavaTM Programming Language|date = 2006-11-02
|access-date = 2008-03-05|first = Danny|last = Coward|publisher = [[Java Community Process]]
|access-date = 2008-03-05|first = Danny|last = Coward|publisher = [[Java Community Process]]
}}
}}</ref>

</ref>
Annotations became available in the language itself beginning with version 1.5 of the [[Java Development Kit]] (JDK). The [[Annotation processing tool|<code>apt</code> tool]] provided a provisional interface for compile-time annotation processing in JDK version 1.5; JSR-269 formalized this, and it became integrated into the [[javac]] compiler in version 1.6.
Annotations became available in the language itself beginning with version 1.5 of the [[Java Development Kit]] (JDK). The [[Annotation processing tool|<code>apt</code> tool]] provided a provisional interface for compile-time annotation processing in JDK version 1.5; JSR-269 formalized this, and it became integrated into the [[javac]] compiler in version 1.6.


Line 26: Line 26:
| title = Predefined Annotation Types
| title = Predefined Annotation Types
| publisher = [[Oracle Corporation]]
| publisher = [[Oracle Corporation]]
| access-date = 2016-12-17
| access-date = 2016-12-17
}}</ref><ref>{{cite web
}}</ref><ref>{{cite web
| url = http://www.java2s.com/Tutorial/Java/0020__Language/TheBuiltInAnnotations.htm
| url = http://www.java2s.com/Tutorial/Java/0020__Language/TheBuiltInAnnotations.htm
| title = The Built-In Annotations : Standard Annotations
| title = The Built-In Annotations : Standard Annotations
| access-date = 2016-12-17
| access-date = 2016-12-17
}}</ref>
}}</ref>


Line 48: Line 48:


* <code>@SafeVarargs</code> - Suppress warnings for all callers of a method or constructor with a [[Generics in Java|generics]] [[Variadic function|varargs]] parameter, since Java 7.
* <code>@SafeVarargs</code> - Suppress warnings for all callers of a method or constructor with a [[Generics in Java|generics]] [[Variadic function|varargs]] parameter, since Java 7.
* <code>@FunctionalInterface </code> - Specifies that the [[Declaration (computer programming)|type declaration]] is intended to be a [[Anonymous function|functional interface]], since Java 8.
* <code>@FunctionalInterface</code> - Specifies that the [[Declaration (computer programming)|type declaration]] is intended to be a [[Anonymous function|functional interface]], since Java 8.
* <code>@Repeatable</code> - Specifies that the annotation can be applied more than once to the same declaration, since Java 8.
* <code>@Repeatable</code> - Specifies that the annotation can be applied more than once to the same declaration, since Java 8.


Line 54: Line 54:


=== Built-in annotations ===
=== Built-in annotations ===
This example demonstrates the use of the <code>@Override</code> annotation. It instructs the compiler to check parent classes for matching methods. In this case, an error is generated because the <code>gettype()</code> method of class Cat doesn't in fact override <code>getType()</code> of class Animal like is desired, because of the [[Case sensitivity|mismatching case]]. If the <code>@Override</code> annotation were absent, a new method of name <code>gettype()</code> would be created in class Cat.
This example demonstrates the use of the <code>@Override</code> annotation. It instructs the compiler to check parent classes for matching methods. In this case, an error is generated because the <code>gettype()</code> method of class Cat doesn't in fact override <code>getType()</code> of class Animal like is desired, because of the [[Case sensitivity|mismatching case]]. If the <code>@Override</code> annotation were absent, a new method of name <code>gettype()</code> would be created in class Cat.


<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
Line 328: Line 328:
* [http://java.sun.com/javase/6/docs/technotes/guides/language/annotations.html Introduction to Java 6 Annotations at Sun Developer Network Site]
* [http://java.sun.com/javase/6/docs/technotes/guides/language/annotations.html Introduction to Java 6 Annotations at Sun Developer Network Site]
* [http://www.developer.com/java/other/article.php/3556176 An Introduction to Java Annotations by M. M. Islam Chisty]
* [http://www.developer.com/java/other/article.php/3556176 An Introduction to Java Annotations by M. M. Islam Chisty]
* [https://web.archive.org/web/20150531080324/http://www.javabeat.net/annotations-in-java-5-0/ Introduction to Java 5.0 Annotations by Joy Christy]
* {{Cite web |last=Srinivasan |first=Krishna |date=August 11, 2007 |title=Annotations in Java 5.0 |url=http://www.javabeat.net/annotations-in-java-5-0/ |url-status=dead |archive-url=https://web.archive.org/web/20150531080324/http://www.javabeat.net/annotations-in-java-5-0/ |archive-date=May 31, 2015 |website=JavaBeat}}
* [http://www.regdeveloper.co.uk/2006/02/24/java_annotations/ Of Java Annotations by John Hunt]
* {{Cite web |last=Hunt |first=John |title=Of Java Annotations |url=https://www.theregister.com/2006/02/24/java_annotations/ |date=24 Feb 2006 |website=The Register |language=en}}
* [https://web.archive.org/web/20140223113106/http://www.somanyword.com/2014/02/how-to-create-and-implement-custom-annotations-in-java/ Custom Annotations in Java]
* {{Cite web |date=February 15, 2014 |title=How to create and implement custom annotations in Java? |url=http://www.somanyword.com/2014/02/how-to-create-and-implement-custom-annotations-in-java/ |url-status=dead |archive-url=https://web.archive.org/web/20140223113106/http://www.somanyword.com/2014/02/how-to-create-and-implement-custom-annotations-in-java/ |archive-date=Feb 23, 2014 |website=So Many Word}}
* [http://www.tutorialsdesk.com/2014/10/java-annotations-tutorial-with-examples.html Java Annotations Explained]
* {{Cite web |date=October 9, 2014 |title=Java Annotations Tutorial with examples |url=http://www.tutorialsdesk.com/2014/10/java-annotations-tutorial-with-examples.html |website=TutorialsDesk}}
* [http://www.javaquery.com/2015/10/understanding-annotations-in-java.html Understanding Annotations in Java]
* {{Cite web |last=Thakor |first=Vicky |date=13 October 2015 |title=Understanding Annotations in Java |url=http://www.javaquery.com/2015/10/understanding-annotations-in-java.html |website=Java by examples}}


<!--Categories-->
<!--Categories-->

Latest revision as of 16:04, 28 June 2024

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code.[1] Classes, methods, variables, parameters and Java packages may be annotated. Like Javadoc tags, Java annotations can be read from source files. Unlike Javadoc tags, Java annotations can also be embedded in and read from Java class files generated by the Java compiler. This allows annotations to be retained by the Java virtual machine at run-time and read via reflection.[2] It is possible to create meta-annotations out of the existing ones in Java.[3]

History[edit]

The Java platform has various ad-hoc annotation mechanisms—for example, the transient modifier, or the @Deprecated javadoc tag. The Java Specification Request JSR-175 introduced the general-purpose annotation (also known as metadata) facility to the Java Community Process in 2002; it gained approval in September 2004.[4]

Annotations became available in the language itself beginning with version 1.5 of the Java Development Kit (JDK). The apt tool provided a provisional interface for compile-time annotation processing in JDK version 1.5; JSR-269 formalized this, and it became integrated into the javac compiler in version 1.6.

Built-in annotations[edit]

Java defines a set of annotations that are built into the language. Of the seven standard annotations, three are part of java.lang, and the remaining four are imported from java.lang.annotation.[5][6]

Annotations applied to Java code:

  • @Override - Checks that the method is an override. Causes a compilation error if the method is not found in one of the parent classes or implemented interfaces.
  • @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used.
  • @SuppressWarnings - Instructs the compiler to suppress the compile time warnings specified in the annotation parameters.

Annotations applied to other annotations (also known as "Meta Annotations"):

  • @Retention - Specifies how the marked annotation is stored, whether in code only, compiled into the class, or available at runtime through reflection.
  • @Documented - Marks another annotation for inclusion in the documentation.
  • @Target - Marks another annotation to restrict what kind of Java elements the annotation may be applied to.
  • @Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited by subclasses).

Since Java 7, three additional annotations have been added to the language.

  • @SafeVarargs - Suppress warnings for all callers of a method or constructor with a generics varargs parameter, since Java 7.
  • @FunctionalInterface - Specifies that the type declaration is intended to be a functional interface, since Java 8.
  • @Repeatable - Specifies that the annotation can be applied more than once to the same declaration, since Java 8.

Example[edit]

Built-in annotations[edit]

This example demonstrates the use of the @Override annotation. It instructs the compiler to check parent classes for matching methods. In this case, an error is generated because the gettype() method of class Cat doesn't in fact override getType() of class Animal like is desired, because of the mismatching case. If the @Override annotation were absent, a new method of name gettype() would be created in class Cat.

public class Animal {
    public void speak() {
    }

    public String getType() {
        return "Generic animal";
    }
}

public class Cat extends Animal {
    @Override
    public void speak() { // This is a good override.
        System.out.println("Meow.");
    }

    @Override
    public String gettype() { // Compile-time error due to typo: should be getType() not gettype().
        return "Cat";
    }
}

Custom annotations[edit]

Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the keyword "interface".

  // @Twizzle is an annotation to method toggle().
  @Twizzle
  public void toggle() {
  }

  // Declares the annotation Twizzle.
  public @interface Twizzle {
  }

Annotations may include a set of key-value pairs, which are modeled as methods of the annotation type. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. Methods can have default values.

  // Same as: @Edible(value = true)
  @Edible(true)
  Item item = new Carrot();

  public @interface Edible {
      boolean value() default false;
  }

  @Author(first = "Oompah", last = "Loompah")
  Book book = new Book();

  public @interface Author {
      String first();
      String last();
  }

Annotations themselves may be annotated to indicate where and when they can be used:

  @Retention(RetentionPolicy.RUNTIME) // Make this annotation accessible at runtime via reflection.
  @Target({ElementType.METHOD})       // This annotation can only be applied to class methods.
  public @interface Tweezable {
  }

The compiler reserves a set of special annotations (including @Deprecated, @Override and @SuppressWarnings) for syntactic purposes.

Annotations are often used by frameworks as a way of conveniently applying behaviours to user-defined classes and methods that must otherwise be declared in an external source (such as an XML configuration file) or programmatically (with API calls). The following, for example, is an annotated JPA data class:

@Entity                                             // Declares this an entity bean
@Table(name = "people")                             // Maps the bean to SQL table "people"
public class Person implements Serializable {
    @Id                                             // Map this to the primary key column.
    @GeneratedValue(strategy = GenerationType.AUTO) // Database will generate new primary keys, not us.
    private Integer id;

    @Column(length = 32)                            // Truncate column values to 32 characters.
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The annotations are not method calls and will not, by themselves, do anything. Rather, the class object is passed to the JPA implementation at run-time, which then extracts the annotations to generate an object–relational mapping.

A complete example is given below:

package com.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,
         ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE,
         ElementType.PACKAGE,ElementType.FIELD,ElementType.LOCAL_VARIABLE})
@Inherited

public @interface Unfinished {
    public enum Priority { LOW, MEDIUM, HIGH }
    String value();
    String[] changedBy() default "";
    String[] lastChangedBy() default "";
    Priority priority() default Priority.MEDIUM;
    String createdBy() default "James Gosling";
    String lastChanged() default "2011-07-08";
}
package com.annotation;

public @interface UnderConstruction {
    String owner() default "Patrick Naughton";
    String value() default "Object is Under Construction.";
    String createdBy() default "Mike Sheridan";
    String lastChanged() default "2011-07-08";
}
package com.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.annotation.UnderConstruction;
import com.annotation.Unfinished;
import com.annotation.Unfinished.Priority;
import com.util.Util;

@UnderConstruction(owner="Jon Doe")
public class DateValidator implements Validator {
	
    public void validate(FacesContext context, UIComponent component, Object value)
        throws ValidatorException {
        String date = (String) value;
        String errorLabel = "Please enter a valid date.";
        if (!component.getAttributes().isEmpty()) {
            errorLabel = (String) component.getAttributes().get("errordisplayval");
        }

        if (!Util.validateAGivenDate(date)) {
            @Unfinished(changedBy = "Steve",
                value = "whether to add message to context or not, confirm",
                priority = Priority.HIGH
            )
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary(errorLabel);
            message.setDetail(errorLabel);
            throw new ValidatorException(message);
        }
    }
}

Processing[edit]

When Java source code is compiled, annotations can be processed by compiler plug-ins called annotation processors. Processors can produce informational messages or create additional Java source files or resources, which in turn may be compiled and processed. However, annotation processors cannot modify the annotated code itself. (Code modifications may be implemented using methods beyond the Java Language Specification.) The Java compiler conditionally stores annotation metadata in the class files, if the annotation has a RetentionPolicy of CLASS or RUNTIME. Later, the JVM or other programs can look for the metadata to determine how to interact with the program elements or change their behavior.

In addition to processing an annotation using an annotation processor, a Java programmer can write their own code that uses reflection to process the annotation. Java SE 5 supports a new interface that is defined in the java.lang.reflect package. This package contains the interface called AnnotatedElement that is implemented by the Java reflection classes including Class, Constructor, Field, Method, and Package. The implementations of this interface are used to represent an annotated element of the program currently running in the Java Virtual Machine. This interface allows annotations to be read reflectively.

The AnnotatedElement interface provides access to annotations having RUNTIME retention. This access is provided by the getAnnotation, getAnnotations, and isAnnotationPresent methods. Because annotation types are compiled and stored in byte code files just like classes, the annotations returned by these methods can be queried just like any regular Java object. A complete example of processing an annotation is provided below:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

// This is the annotation to be processed
// Default for Target is all Java Elements
// Change retention policy to RUNTIME (default is CLASS)
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeHeader {
    // Default value specified for developer attribute
    String developer() default "Unknown";
    String lastModified();
    String [] teamMembers();
    int meaningOfLife();
}
// This is the annotation being applied to a class
@TypeHeader(developer = "Bob Bee",
    lastModified = "2013-02-12",
    teamMembers = { "Ann", "Dan", "Fran" },
    meaningOfLife = 42)

public class SetCustomAnnotation {
    // Class contents go here
}
// This is the example code that processes the annotation
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;

public class UseCustomAnnotation {
    public static void main(String [] args) {
        Class<SetCustomAnnotation> classObject = SetCustomAnnotation.class;
        readAnnotation(classObject);
    }

    static void readAnnotation(AnnotatedElement element) {
        try {
            System.out.println("Annotation element values: \n");
            if (element.isAnnotationPresent(TypeHeader.class)) {
                // getAnnotation returns Annotation type
                Annotation singleAnnotation = 
                        element.getAnnotation(TypeHeader.class);
                TypeHeader header = (TypeHeader) singleAnnotation;

                System.out.println("Developer: " + header.developer());
                System.out.println("Last Modified: " + header.lastModified());

                // teamMembers returned as String []
                System.out.print("Team members: ");
                for (String member : header.teamMembers())
                    System.out.print(member + ", ");
                System.out.print("\n");

                System.out.println("Meaning of Life: "+ header.meaningOfLife());
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

See also[edit]

References[edit]

  1. ^ "Annotations". Sun Microsystems. Archived from the original on 2011-09-25. Retrieved 2011-09-30..
  2. ^ Sun Microsystems (2005). Java(TM) Language Specification (3rd ed.). Prentice Hall. ISBN 0-321-24678-0..
  3. ^ Dare Obasanjo (2007). "A COMPARISON OF MICROSOFT'S C# PROGRAMMING LANGUAGE TO SUN MICROSYSTEMS' JAVA PROGRAMMING LANGUAGE: Metadata Annotations". Dare Obasanjo. Archived from the original on 2012-09-19. Retrieved 2012-09-20.
  4. ^ Coward, Danny (2006-11-02). "JSR 175: A Metadata Facility for the JavaTM Programming Language". Java Community Process. Retrieved 2008-03-05.
  5. ^ "Predefined Annotation Types". Oracle Corporation. Retrieved 2016-12-17.
  6. ^ "The Built-In Annotations : Standard Annotations". Retrieved 2016-12-17.

External links[edit]