The above thought map is: http://download.csdn.net/detail/emilyrr/8975487
- Notes for Annotations:
-
Through the above study, we can use meta-annotations to implement a custom HelloWorld annotation
-
First step: Define a HelloWorld annotation
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)//定义了注解的作用位置:在方法上@Inherited//允许子类继承父类中的注解public @interface HelloWorld { publicname()default "";}
- Create a new annotation resolution class, which is implemented by reflection mechanism
publicclass ParseAnnotation { publicvoidparseMethod(Class clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{ Object obj = clazz.newInstance(); Method[] methods=clazz.getDeclaredMethods(); for(Method m:methods){ HelloWorld hello=m.getAnnotation(HelloWorld.class); String name=""; if(hello!=null){ name=hello.name(); m.invoke(obj, name); } } }}
- Create a new normal class, call HelloWorld annotations
publicclass SayHello { @HelloWorld(name="Yc") publicvoidsay(String name){ ifnull || name.equals("")){ System.out.println("hello world"); }else{ System.out"hello world\t"+name); } }}
- Use JUnit tests (create a new class, test in the Main method)
publicvoidtestAppthrows InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { ParseAnnotation pa=new ParseAnnotation(); pa.parseMethod(SayHello.class); }
- Let's look at the test results:
As can be seen from the test class, we do not have a direct new SayHello object, or a say () method that calls it, but a say that is activated by the reflection mechanism through the annotation's parsing framework. "The age of change in this code," said the brother.
Copyright NOTICE: This article for Bo Master original article, thank you for reference! Where there is a problem, you are welcome to correct and progress together.
Java annotation detailed + custom Java annotations (i)