Java annotation Learning

Source: Internet
Author: User
Document directory
  • Modify the retention of assignment to view the class file of demo1 after compilation.
@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override {} 

@ Interface: declares that this is an annotation.

@ Retention: Declares the annotation policy. For details, see retentionpolicy. Source

Public Enum retentionpolicy {## # saved in the source code will be discarded by the compiler, ### effective during compilation, which will have a certain impact on the final class generated by the Code, it is not retained during running. This value is the default value of class, ### it takes effect during compilation, and will have a certain impact on the final class generated by the code. It is retained during runtime and is usually read through reflection. Runtime}

@ Target: Specifies the elements that the annotation can be placed on. For details, see elementtype.

To add a variable named age, the Code is as follows:

@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override {  int age();} 


Write a retentionpolicy = Class annotation and use javac to try the annotation.
@Retention(RetentionPolicy.CLASS)@Target(ElementType.TYPE)public @interface Assignment {    String assignee();} 

Process Annotation

@SupportedSourceVersion(SourceVersion.RELEASE_6)@SupportedAnnotationTypes("Assignment")public class AssignmentProcess extends AbstractProcessor {    private TypeElement assignmentElement;     public synchronized void init(ProcessingEnvironment processingEnv) {        super.init(processingEnv);        Elements elementUtils = processingEnv.getElementUtils();        assignmentElement = elementUtils.getTypeElement("Assignment");    }     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(assignmentElement);        for (Element element : elements) {            System.out.println(element);        }        return true;    }}  

@Assignment(assignee = "123")public class Demo1 {}

Run:

javac -processor AssignmentProcess Demo1.javaDemo1

In principle, everything is normal, but the tragedy is that the retention of the annotation can still be executed. According to the previous understanding, the source should not be read in the compiler.

@Retention(RetentionPolicy.SOURCE)

Modify the retention of assignment. After compilation, the class file of demo1 looks quite normal. @ retention (retentionpolicy. Source)

public class Demo1 extends java.lang.Object  SourceFile: "Demo1.java"

@ Retention (retentionpolicy. Class)

public class Demo1 extends java.lang.Object  SourceFile: "Demo1.java"  RuntimeInvisibleAnnotations: length = 0xB   00 01 00 0B 00 01 00 0C 73 00 0D 

@ Retention (retentionpolicy. runtime)

public class Demo1 extends java.lang.Object  SourceFile: "Demo1.java"  RuntimeVisibleAnnotations: length = 0xB   00 01 00 0B 00 01 00 0C 73 00 0D 

Locate the problem and wait for research. Write a retentionpolicy = runtime annotation.

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface RoleCheck {    String role();} 
Handle, obtains annotation information through reflection internally to verify whether this method can be called
Public class accessinvocationhandler implements invocationhandler {final object accessobj; Public accessinvocationhandler (Object accessobj) {This. accessobj = accessobj;} public object invoke (Object proxy, method, object [] ARGs) throws throwable {rolecheck annotation = method. getannotation (rolecheck. class); // obtain the annotation if (annotation! = NULL) {string role = annotation. Role (); If (! Stringutil. equals (role, currentroleutil. getcurrentrole () {Throw new accesscontrolexception ("the user is not allowed to invoke this method. ");} return method. invoke (accessobj, argS);} else {Throw new accesscontrolexception ("the user is not allowed to invoke this method. ");}}}

Simulate cache and other tools to obtain the currently executed role

public class CurrentRoleUtil {    private static int cur = 0;    public static String getCurrentRole(){        if(cur%2==0){            ++cur;            return "guanfei";        }        ++cur;        return "hake";    }}

Called by proxy

    public static void main(String[] args) {        HelloWorld hello = new HelloWorldImpl();        InvocationHandler handler = new AccessInvocationHandler(hello);        HelloWorld proxy = (HelloWorld)Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler);        proxy.sayHello();        proxy.sayHello();    }

Execution result

Hello World!Exception in thread "main" java.security.AccessControlException: The user is not allowed to invoke this method.at AccessInvocationHandler.invoke(AccessInvocationHandler.java:20)at $Proxy0.sayHello(Unknown Source)at Test.main(Test.java:11)
If the @ retention (retentionpolicy. Class)
Exception in thread "main" java.security.AccessControlException: The user is not allowed to invoke this method.at AccessInvocationHandler.invoke(AccessInvocationHandler.java:24)at $Proxy0.sayHello(Unknown Source)at Test.main(Test.java:9)

This comment cannot be obtained through reflection.

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.