How Do Annotations Work in Java?--转
原文地址:https://dzone.com/articles/how-annotations-work-java
Annotations have been a very important part of Java and it’s been there from the time of J2SE 5.0. All of us might have seen annotations like @Override and @Deprecated in our application code at some place or another. In this article I will discuss what exactly annotations are, why they were introduced, how they work, how to write custom annotations (with example code), what could be valid scenarios for annotations and lastly Annotations and ADF. It’s going to be a long post, so get a mug of coffee and get ready to dive into world of annotations.
What are Annotations?
One word to explain Annotation is Metadata. Metadata is data about data. So Annotations are metadata for code. For example look at following piece of code.
@Override
public String toString() {
return "This is String Representation of current object.";
}
Annotation is special kind of Java construct used to decorate a class, method, field, parameter, variable, constructor, or package. It’s the vehicle chosen by JSR-175 to provide metadata.
Why Were Annotations Introduced?
Prior to annotation (and even after) XML were extensively used for metadata and somehow a particular set of Application Developers and Architects thought XML maintenance was getting troublesome. They wanted something which could be coupled closely with code instead of XML which is very loosely coupled (in some cases almost separate) from code. If you google “XML vs. annotations”, you will find a lot of interesting debates. Interesting point is XML configurations were introduced to separate configuration from code. Last two statements might create a doubt in your mind that these two are creating a cycle, but both have their pros and cons. Let’s try to understand with an example.
Suppose, you want to set some application wide constants/parameters. In this scenario, XML would be a better choice because this is not related with any specific piece of code. If you want to expose some method as a service, annotation would be a better choice as it needs to be tightly coupled with that method and developer of the method must be aware of this.
Another important factor is that annotation defines a standard way of defining metadata in code. Prior to annotations people also used their own ways to define metadata. Some examples are – using marker interfaces, comments, transient keywords etc. Each developer decided his own way to decide metadata, but annotation standardized things.
These days most frameworks use combination of both XML and Annotations to leverage positive aspects of both.
How Annotations Work and How to Write Custom Annotations
Before I start this explanation, I will suggest you download this sample code for annotations (AnnotationsSample.zip) and keep that open in any IDE of your choice, as it will help you to understand following explanation better.
Writing annotations is very simple. You can compare annotation definition to an interface definition. Let’s have a look at two examples – One is standard @Override annotation and second is a custom annotation @Todo
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
Something seems fishy about @Override, it’s not doing anything, how it checks if a method is defined in parent class. Well, don’t be surprised, I am not kidding you. Override annotation’s definition has that much code only. This is the most important part to understand and I am reiterating myself – Annotations are only metadata and they do not contain any business logic. Tough to digest but true. If annotations do not contain the logic than someone else must be doing something and that someone is consumer of this annotation metadata. Annotations only provide some information about the attribute (class/method/package/field) on which it is defined. Consumer is a piece of code which reads this information and then performs necessary logic.
When we are talking about standard annotations like @Override – JVM is the consumer and it works at bytecode level. Now that’s something application developers can’t control and can’t use for custom annotations. So we need to write consumers for our annotations by ourselves.
Let’s understand the key terms used for writing annotations one by one. In the above examples, you will see annotations are used on annotations.
J2SE 5.0 provides four annotations in the java.lang.annotation package that are used only when writing annotations:
@Documented – Whether to put the annotation in Javadocs
@Retention – When the annotation is needed
@Target? – Places the annotation can go
@Inherited – Whether subclasses get the annotation.
@Documented – A simple market annotations which tells whether to add Annotation in java doc or not.
@Retention – Defines for how long the annotation should be kept.
RetentionPolicy.SOURCE – Discard during the compile. These annotations don’t make any sense after the compile has completed, so they aren’t written to the bytecode. Examples @Override, @SuppressWarnings
RetentionPolicy.CLASS – Discard during class load. Useful when doing bytecode-level post-processing. Somewhat surprisingly, this is the default.
RetentionPolicy.RUNTIME – Do not discard. The annotation should be available for reflection at runtime. This is what we generally use for our custom annotations.
@Target – Where annotation can be placed. If you don’t specify this, annotation can be placed anywhere. Following are the valid values. One important point here is, it’s inclusive only which means if you want annotation on 7 attributes and just want to exclude only one attribute, you need to include all 7 while defining target.
ElementType.TYPE (class, interface, enum)
ElementType.FIELD (instance variable)
ElementType.METHOD
ElementType.PARAMETER
ElementType.CONSTRUCTOR
ElementType.LOCAL_VARIABLE
ElementType.ANNOTATION_TYPE (on another annotation)
ElementType.PACKAGE (remember package-info.java)
@Inherited – Controls whether annotation should affect subclass.
Now what goes inside an annotation definition? Annotations only support primitives, string and enumerations. All attributes of annotations are defined as methods and default values can also be provided
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo {
public enum Priority {LOW, MEDIUM, HIGH}
public enum Status {STARTED, NOT_STARTED}
String author() default "Yash";
Priority priority() default Priority.LOW;
Status status() default Status.NOT_STARTED;
}
Following is an example of how the above annotation can be used
@Todo(priority = Todo.Priority.MEDIUM, author = "Yashwant", status = Todo.Status.STARTED)
public void incompleteMethod1() {
//Some business logic is written
//But it’s not complete yet
}
If we have only one attribute inside an annotation, it should be named “value” and can be used without attribute name while using it.
@interface Author{
String value();
}
@Author("Yashwant")
public void someMethod() {
}
So far so good. We have defined our custom annotation and applied it to some business logic methods. Now it’s time to write a consumer. For that we will need to use Reflection. If you are familiar with Reflection code, you know reflection provides Class, Method and Field objects. All of these have a getAnnotation() method which returns the annotation object. We need to cast this object as our custom annotation (after checking with instanceOf()) and then we can call methods defined in our custom annotation. Let’s look at the sample code, which uses above annotation:
Class businessLogicClass = BusinessLogic.class;
for(Method method : businessLogicClass.getMethods()) {
Todo todoAnnotation = (Todo)method.getAnnotation(Todo.class);
if(todoAnnotation != null) {
System.out.println(" Method Name : " + method.getName());
System.out.println(" Author : " + todoAnnotation.author());
System.out.println(" Priority : " + todoAnnotation.priority());
System.out.println(" Status : " + todoAnnotation.status());
}
}
Use Cases for Annotations
Annotations are very powerful and Frameworks like spring and Hibernate use Annotations very extensively for logging and validations. Annotations can be used in places where marker interfaces are used. Marker interfaces are for the complete class but you can define annotation which could be used on individual methods for example whether a certain method is exposed as service method or not.
In latest servlet specification 3.0 a lot of new Annotations are introduced, especially related with servlet security.
HandlesTypes – This annotation is used to declare an array of application classes which are passed to a ServletContainerInitializer.
HttpConstraint – This annotation represents the security constraints that are applied to all requests with HTTP protocol method types that are not otherwise represented by a corresponding HttpMethodConstraint in a ServletSecurity annotation.
HttpMethodConstraint – Specific security constraints can be applied to different types of request, differentiated by the HTTP protocol method type by using this annotation inside the ServletSecurity annotation.
MultipartConfig – This annotation is used to indicate that the Servlet on which it is declared expects requests to made using the multipart/form-data MIME type.
ServletSecurity – Declare this annotation on a Servlet implementation class to enforce security constraints on HTTP protocol requests.
WebFilter – The annotation used to declare a Servlet Filter.
WebInitParam – The annotation used to declare an initialization parameter on a Servlet or Filter, within a WebFilter or WebServlet annotation.
WebListener -The annotation used to declare a listener for various types of event, in a given web application context.
WebServlet – This annotation is used to declare the configuration of an Servlet.
ADF (Application Development Framework) and Annotations
Now we are at the last part of our discussion. Application Development Framework, also known as ADF, is developed by Oracle and used to build Oracle Fusion Application. We have seen pros and cons, we know how to write custom annotations but where to use custom annotations in ADF? Does ADF provide any native Annotations? Interesting questions, but there are certain limitations that prevent usage of annotation to a large scale in ADF. Frameworks which are mentioned earlier like spring and Hibernate, use AOP (Aspect oriented programming). In AOP, framework provides mechanism to inject code for preProcessing and postProcessing for any event. For example, you have a hook to place code before and after a method execution, so you can write your consumer code in those places. ADF does not use AOP. If we have any valid use case for annotations, we might need to go via inheritance way.
Hope you enjoyed this article. Please drop in your comments.
Source : How Annotations Work In Java
How Do Annotations Work in Java?--转的更多相关文章
- Java custom annotations
Custom annotation definition is similar as Interface, just with @ in front. Annotation interface its ...
- Java.Annotations
Annotation 0. Annotation Tricks http://developer.android.com/reference/java/lang/annotation/Annotati ...
- 【译】Core Java Questions and Answers【1-33】
前言 译文链接:http://www.journaldev.com/2366/core-java-interview-questions-and-answers Java 8有哪些重要的特性 Java ...
- [Android]使用自定义JUnit Rules、annotations和Resources进行单元测试(翻译)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5795091.html 使用自定义JUnit Rules.ann ...
- java stopwatch 功能
C#中有一个stopwatch的功能,主要是用来监测程序执行时间的.java之前一直都在用如下方式完成: public static void main(String[] args) { long s ...
- Java中的反射和注解
前言 在Java中,反射机制和注解机制一直是一个很重要的概念,那么他们其中的原理是怎么样呢,我们不仅仅需要会使用,更要知其然而之所以然. 目录 反射机制 反射如何使用 注解定义 注解机制原理 注解如何 ...
- 使用Gson转换json数据为Java对象的一个例子
记录工作中碰到的一个内容. 原料是微信平台的一个接口json数据. { "errcode" : 0, "errmsg" : "ok", &q ...
- How do annotations work internally--转
原文地址:http://stackoverflow.com/questions/18189980/how-do-annotations-work-internally The first main d ...
- Java Hour 65 [译] Java 6.0 说明
原文可爱的地址: http://www.javabeat.net/introduction-to-java-6-0-new-features-part-i/ 该文字2007年的,现在估计老掉牙了,但是 ...
随机推荐
- 深入剖析Nginx一点小笔记
前几天在图书馆看书,恰好看到这本<深入剖析nginx>,花了快一周的时间看完了这本书,写点笔记心得便于以后复习. 以前对nginx的认识就只是停留在一个反向代理服务器上.百度了一下ngin ...
- PyQt4学习资料汇总
一个月前研究了下PyQt4,感觉比较不错.相比wxpython,界面美观了很多,并且将界面设计与代码逻辑很好的分离了开来.关于PyQt4的资料也不少,这里我将我找到的资料汇总一下,以防自己以后忘得一干 ...
- 微小企业中Sqlserver2000服务器的日常备份与恢复
1:把数据库和备份分别放在二个硬盘上 2:不要相信用户会使用客户端坚持备份数据,比较靠谱的方法是为数据库建立维护计划 3:数据库采用每天完全备份,并且时间一定要选择在用户肯定开机的时候,因为很多用户晚 ...
- Oracle Created (Default) Database Users
http://www.idevelopment.info/data/Oracle/DBA_tips/Database_Administration/DBA_26.shtml DBA Tips Arch ...
- ASP.NET 4.5.256 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.5.256 in order for your site to run correctly
Microsoft .NET Framework 4.6安装后,用户可能会在使用Microsoft Visual Studio 创建(或打开现有项目时)网站.或Windows Azure项目时遇到下面 ...
- HTTP基本认证
众所周知,Web使人们可以很方便的访问分布在世界各个角落里信息.但是仅仅是方便还是不够的,并不是所有的信息都适合在互联网上公开访问,我们需要保证只有特定的人才能看到我们的敏感信息并且执行特定的操作. ...
- 第一个 Asp.Net vNext 应用程序
要说免费的虚拟主机的话,最好的服务商应该就是Microsoft Azure(不是Windows Azure由世纪互联运营),提供免费的1GB .NET/Java/Python/Php空间,日流量有限制 ...
- RCP:给GEF编辑器添加拖拽辅助线
当图形边缘碰触时,会产生一条帮助拖拽的辅助线 这里需要三个类: 1.SnapToGeomotry 2.SnapToGuide(非必须) 3.SnapFeedbackPolicy
- Java多线程系列--“JUC锁”06之 Condition条件
概要 前面对JUC包中的锁的原理进行了介绍,本章会JUC中对与锁经常配合使用的Condition进行介绍,内容包括:Condition介绍Condition函数列表Condition示例转载请注明出处 ...
- java提高篇(二四)-----HashSet
在前篇博文中(java提高篇(二三)-----HashMap)详细讲解了HashMap的实现过程,对于HashSet而言,它是基于HashMap来实现的,底层采用HashMap来保存元素. ...