Turn! Java Custom Annotations

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/yixiaogang109/article/details/7328466

Java annotations are some of the meta-information that is attached to the code, used by some tools to parse and use at compile and run time, to illustrate and configure Functionality.
Annotations do not and do not affect the actual logic of the code, only the ancillary role. Included in the Java.lang.annotation Package.

1, Yuan Annotation

Meta annotations are annotations of Annotations. including @Retention @Target @Document @Inherited four KINDS.


1.1. @Retention: define retention policies for annotations

@Retention (retentionpolicy.source)//annotations only exist in the source code and do not contain @Retention (retentionpolicy.class)//default retention policy in the CLASS bytecode File. Annotations exist in a class bytecode file, but are not available at runtime, @Retention (retentionpolicy.runtime)//annotations exist in a class bytecode file and can be obtained at runtime by reflection at 1.2, @ Target: define the purpose of the annotation the source code for its definition is: [java]View PlainCopy
    1. @Documented
    2. @Retention (retentionpolicy.runtime)
    3. @Target (elementtype.annotation_type)
    4. Public @interface Target {
    5. elementtype[] value ();
    6. }
@Target (elementtype.type)//interfaces, classes, enumerations, annotations @Target (elementtype.field)//fields, constants of enumerations @Target (elementtype.method)// Method @target (elementtype.parameter)//method parameter @target (elementtype.constructor)//constructor @target (elementtype.local_variable ///local variable @target (elementtype.annotation_type)//note @target (elementtype.package)///package by the above source can be known, his elementtype can have multiple, An annotation can be a class, a method, a field, and so on 1.3, @Document: Note that the note will be included in Javadoc 1.4, @Inherited: The description subclass can inherit from the parent class of the note 2, the Java annotations are customized below is an example of a custom annotation [java]View PlainCopy
    1. @Documented
    2. @Target ({elementtype.type,elementtype.method})
    3. @Retention (retentionpolicy.runtime)
    4. Public @interface Yts {
    5. public enum ytstype{util,entity,service,model}
    6. public ytstype ClassType () default ytstype.util;
    7. }
[java]View PlainCopy
    1. @Documented
    2. @Retention (retentionpolicy.runtime)
    3. @Target (ELEMENTTYPE.METHOD)
    4. @Inherited
    5. Public @interface HelloWorld {
    6. public String name ()default "";
    7. }

@Retention (retentionpolicy.runtime)

The annotation defined is that the annotations exist in the class bytecode file and can be obtained through reflection at run Time.

@Target ({elementtype.type,elementtype.method})

So this annotation can be a class annotation, or it can be an annotation of a method.

Such an annotation is customized, of course, the members of the annotation can be the basic data type, but also for the data, object, and so on

3 The annotations are defined, so how do we get them and parse the annotations?

The reflection mechanism of Java can help, get annotations, the code is as Follows:

[java]View PlainCopy
  1. Public class Parseannotation {
  2. public void Parsemethod (Class clazz) throws illegalargumentexception, illegalaccessexception, invocationtargetexception, securityexception, nosuchmethodexception, instantiationexception{
  3. Object obj = clazz.getconstructor (new class[]{}). newinstance (new object[]{});
  4. for (Method method:clazz.getDeclaredMethods ()) {
  5. HelloWorld say = Method.getannotation (HelloWorld.   class);
  6. String name = "";
  7. if (say! = Null) {
  8. Name = Say.name ();
  9. Method.invoke (obj, name);
  10. }
  11. Yts Yts = (yts) method.getannotation (yts.   class);
  12. if (yts! = Null) {
  13. if (YtsType.util.equals (yts.classtype ())) {
  14. System.out.println ("this is a util method");
  15. }else{
  16. System.out.println ("this was a other method");
  17. }
  18. }
  19. }
  20. }
  21. @SuppressWarnings ("unchecked")
  22. public void Parsetype (Class clazz) throws illegalargumentexception, illegalaccessexception, invocationtargetexception{
  23. Yts Yts = (yts) clazz.getannotation (yts.   class);
  24. if (yts! = Null) {
  25. if (YtsType.util.equals (yts.classtype ())) {
  26. System.out.println ("this is a util class");
  27. }else{
  28. System.out.println ("this was a other class");
  29. }
  30. }
  31. }
  32. }

The previous method is to parse the method annotation, the latter method is to get the class annotation

The following is the test method class

[java]View PlainCopy
  1. @Yts (classtype =ytstype.util)
  2. Public class Sayhell {
  3. @HelloWorld (name = "xiaoming")
  4. @Yts
  5. public void SayHello (String Name) {
  6. if (name = = Null | | name.equals (")") {
  7. System.out.println ("hello world!");
  8. }else{
  9. System.out.println (name + "say Hello world!");
  10. }
  11. }
  12. }

[html]View PlainCopy
      1. public static void main (string[] Args) throws illegalargumentexception, illegalaccessexception, invocationtargetexception, securityexception, nosuchmethodexception, instantiationexception {
      2. Parseannotation parse = new Parseannotation ();
      3. Parse.parsemethod (sayhell.class);
      4. Parse.parsetype (sayhell.class);
      5. }

Turn! Java Custom Annotations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.