日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

How Do Annotations Work in Java?--转

發布時間:2025/4/5 java 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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."; } I have overridden the toString() method and used @Override annotation in above code. Even if I don’t put @Override, code works properly without any issue. So what’s the advantage and what does this annotation stand for? @Override tells the compiler that this method is an overridden method (metadata about method) and if any such method does not exist in parent class, then throw a compiler error (method does not override a method from its super class). Now if I would have made a typography mistake and used method name as toStrring() {double r} and if I wouldn’t have used @Override, my code would have compiled and executed successfully but outcome would be different from what I would have accepted. So now we understand what annotations are but still it’s good to read formal definitions

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?

?

轉載于:https://www.cnblogs.com/davidwang456/p/5564082.html

總結

以上是生活随笔為你收集整理的How Do Annotations Work in Java?--转的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 久久精品老司机 | 男人看片网站 | 精品国产96亚洲一区二区三区 | 男女免费网站 | 天天操天天爽天天干 | 色婷婷视频网 | 日韩欧美精品在线视频 | 一级欧美一级日韩片 | 少妇又紧又色又爽又刺激 | 天堂a视频| 国产亚洲欧美一区二区三区 | 中文字幕在线播放视频 | 日韩欧美一区二区三区四区五区 | 久久久久一区 | mm1313亚洲精品 | www婷婷 | 日韩激情电影在线 | 芒果视频污污 | 韩日中文字幕 | 伊人中文在线 | 青青久操| 日韩中文网 | 男女做的视频 | 青青草原伊人网 | 亚洲精品乱码久久久久久蜜桃动漫 | 精品中文字幕视频 | 大学生高潮无套内谢视频 | av集中营 | 波多野结衣在线视频播放 | 亚洲一级无毛 | 大乳丰满人妻中文字幕日本 | 日本熟女一区二区 | 美女又爽又黄又免费 | 成人av激情 | 青娱乐激情 | www..com色| 国产黄色网页 | 欧美精品xx | 亚洲成人久 | 国产夫妻性生活视频 | 秋霞福利视频 | 天天做天天摸天天爽天天爱 | 污视频91 | 在线免费看黄色片 | 制服丝袜亚洲 | 三级国产在线 | 一区二区三区在线观看av | 免费在线黄色网 | 久久久久一级片 | 99久久99久久精品国产片桃花 | 日韩在线观看av | 国产ts变态重口人妖hd | 午夜8888 | 色婷婷精品国产一区二区三区 | 日韩精品一区在线 | 操欧美女| 国产精品99久久久久久久久久久久 | 秋霞欧美在线观看 | 日韩九九九 | 一区二区三区韩国 | 奇米在线观看 | 亚洲成人手机在线 | 午夜剧场欧美 | 精品人妻大屁股白浆无码 | 国产精品美女视频 | 欧美在线视频播放 | 黄色在线视频网址 | 日韩岛国片 | 午夜做爰xxxⅹ性高湖视频美国 | 欧美69式性猛交 | 国产性爱精品视频 | 99久久精品国产色欲 | 日韩精品2 | 成人性做爰片免费视频 | 亚洲色图10p | 欧美成人aaa片一区国产精品 | 欧美成人aaaa | 一区二区三区视频在线免费观看 | 成人免费高清视频 | 视频在线观看你懂的 | 深夜视频在线免费 | 亚洲国产精品久久久久久 | 女性向av免费网站 | 亚洲大片免费看 | 国产精品无码毛片 | 在线播放黄色av | 91麻豆国产福利精品 | 久热中文 | 伊人网视频在线 | 国产色一区 | 四虎最新站名点击进入 | 色哟哟中文字幕 | 日韩av一区二区三区在线 | 91理论片| 日本中文字幕影院 | 亚洲午夜激情视频 | 亚洲av无码专区国产乱码不卡 | 日本久久一区 | 日本视频在线观看 |