Annotation and Annotation Types
The first step in the post is defining an annotation type. This is pretty simple to do and looks familiar as well. An annotation-type declaration looks like an interface declaration except an "@" symbol precedes the interface keyword. The method declaration
that goes between the braces of this declaration defines the elements of the annotation type. Of course, since we are annotating the code and not defining behavior, logically speaking, these methods shouldn't throw any exception. That means no throws clause.
Another restriction is that the return type for these methods is restricted to primitives: String, Class, enums, annotations and arrays of the preceding types. The complete lists of restrictions are as follows:
- No extends clause is permitted.Annotation types automatically extend a marker interface, java.lang.annotation.Annotation.
- Methods must not have any parameters.
- Methods must not have any type parameters (in other words, generic methods are prohibited).
- Method return types are restricted to primitive types: String, Class, enum types, annotation types and arrays of the preceding types.
- No throws clause is permitted.
- Annotation types must not be parameterized.
The following code snippet defines an annotation type for a servlet. Presumably, we could use this definition to annotate a servlet and then have an annotation tool generate web.xml. Here we define
no args methods that define the various XML attributes/elements found in web.xml. For conciseness we have left out elements like init, load on startup, icon etc.
public @interface Servlet {
String servletName();
String servletClass();
String displayName();
String description();
}
Declaring AnnotationNow that we have the annotation-type defined we can annotate our servlet using the defined annotation type. Annotation is a new kind of modifier that contains an annotation type with zero or more member-value
pairs. If a member has a default value defined in the annotation-type member declaration then the value can be omitted, otherwise, annotation must provide a member-value pair for all members defined in the annotation type. Annotation can be used for modifiers
in any declaration - class, interface, constructor, method, field, enum, even local variable. It can also be used on a package declaration provided only one annotation is permitted for a given package. In our case we are annotating at the class level and the
annotation precedes the access modifier public.
@Servlet(
servletName="AnnotatedServet",
servletClass="com.wonder.servlet.AnnotatedServet",
displayName="AnnotatedServet",
description="This is an example Annotated Servlet"
)
public class AnnotatedServet extends HttpServlet{...}
Annotation Retention
The consumers of annotation fall into three categories.
-
Introspectors: Programs that query runtime-visible annotations of their own program elements. These programs will load both annotated classes and annotation interfaces into the virtual machine.
-
Specific Tools: Programs that query known annotation types of arbitrary external programs. Stub generators, for example, fall into this category. These programs will read annotated classes without loading them into the virtual machine, but will
load annotation interfaces.
-
General Tools: Programs that query arbitrary annotations of arbitrary external programs (such as compilers, documentation generators and class browsers). These programs will load neither annotated classes nor annotation interfaces into the virtual
machine.
The grouping of annotation consumers mentioned above is determined by the retention policy that is specified by the RetentionPolicy enum present in the java.lang.annotation package. If the retention
policy is 'CLASS' then the annotations are recorded in the class files but are not retained by the virtual machine. If the retention policy is 'RUNTIME' then the annotations are recorded in the class file and are retained by the VM at run-time. The value 'SOURCE'
causes the compiler and VM to discard the annotation.
Annotation Processing Tool
The annotation processing tool (apt) found in JAVA_HOME/bin directory is a command-line utility that ships with JDK 5.0. This tool looks for annotation processors based on the annotation in the set of specified source files being examined. Essentially the annotation
processor uses a set of reflective APIs and supporting infrastructure to process the annotations.
When invoked, the apt goes through the following sequence of operations: First, it determines what annotations are present in the source code being operated on. Next, it looks for annotation processor
factories. It then asks the factories what annotations they process and, if the factory processes an annotation present in source files being operated on, the apt asks the factory to provide an annotation processor. Next, the annotation processors are run.
If the processors have generated new source files, the apt will repeat this process until no new source files are generated. This high-level sequence is indicated in Figure 1.
To write a factory class, a developer has to rely on packages that aren't part of the standard SDK. The packages used are:
-
com.sun.mirror.apt: interfaces to interact with the tool.
-
com.sun.mirror.declaration: interfaces to model the source code declarations of fields, methods, classes, etc.
-
com.sun.mirror.type: interfaces to model types found in the source code.
-
com.sun.mirror.util: various utilities for processing types and declarations, including visitors.
These packages are bundled in tools.jar, and so this jar file needs to be set in the classpath to write and compile the factory class. Assuming that the path and the classpath are set correctly, the
annotation processing tool can be invoked from the command prompt by typing 'apt' followed by the tools command-line parameters.
分享到:
相关推荐
In Pro CDI 2 in Java EE 8, use CDI and the CDI 2.0 to automatically manage the life cycle of your enterprise Java, Java EE, or Jakarta EE application’s beans using predefined scopes and define custom...
and specifically know how to use and apply Java annotations. If you are unfamiliar with the Java language, I recommend Learning Java by Patrick Niemeyer and Jonathan Knudsen (O’Reilly).
Work in Progress Please note that this is still work in progress!...For koltin project (android or pure) use kotlin-kapt plugin and use kapt instead of annotationProcessor in dependencies section of
Now, Core Java®, Volume II—Advanced Features, Tenth Edition, has been extensively updated to reflect the most eagerly awaited and innovative version of Java in years: Java SE 8. Rewritten and ...
1、How to create and destroy objects 2、Using methods common to all objects 3、How to design Classes and Interfaces 4、How and when to use Generics ...14、Java Annotation Processors 15、Java Agents
Arrays in Java .............................. 44 You never need to destroy an object .................. 45 Scoping ........................................ 45 Scope of objects ...........................
Item 40: Consistently use the Override annotation Item 41: Use marker interfaces to define types 7 Lambdas and Streams Item 42: Prefer lambdas to anonymous classes Item 43: Prefer method references to...
or changes to classes and methods caused by the addition of generics (such as the collections utilities and the reflection classes)change permeates this entire fourth edition. <br>The Java ...
The ICEpdf API is 100% Java, lightweight, fast, efficient, and very easy to use. ICEpdf can be used as standalone open source Java PDF viewer, or can be easily embedded in any Java application to ...
With relevant examples, careful explanations of Groovy's key concepts and features, and insightful coverage of how to use Groovy in-production tasks, including building new applications, integration ...
The Java Development Kit (JDK) APIs are specific to the JDK and will not necessarily be available in all implementations of the Java SE Platform. These APIs are in modules whose names start with jdk....
in Java. It focuses on methods' mapping, invoking, intercepting and result processing. You can use it to search and collect your application objects' methods for HTTP controller, Web services, RPC, a ...
expression to the @MethodPattern annotation in LintDetectorStats.java, you might see a line like this. Conversely, it's a good sign if you see a line like this. If you make code changes to the tool, ...
AnnotationProcessorJava annotation processor demo.1.Compile - 编译方法一执行mvn clean compile命令编译项目,可在Client子模块下可查看编译日志compile.... you may not use this file except in compliance with
All the examples shown in this book use Spring 4. You can download the examples (consisting of 60 sample projects) described in this book from the following Google Code project: code.google....
annotation-based implementation class library for Android dynamic permission requests, which allows developers to adapt Android dynamic permissions with as little code as possible. Use Scene 如果您的...
DebugAlter Alter Android app behavior without rebuild when debugging. ...(You can use this library in Kotlin and Java!) app/src/main/java/com/../MainActivity.kt class MainActivity : A
NullAway: Fast Annotation-Based Null Checking for Java NullAway is a tool to help eliminate NullPointerExceptions (NPEs) in your Java code. To use NullAway, first add @Nullable annotations in your ...
NullAway: Fast Annotation-Based Null Checking for Java NullAway is a tool to help eliminate NullPointerExceptions (NPEs) in your Java code. To use NullAway, first add @Nullable annotations in your ...
javax.persistence.spi The javax.persistence.spi package defines the classes and interfaces that are implemented by the persistence provider and the Java EE container for use by the container, provider...