自定义Annotation入门例子

1.首先,定义自己的Annotation。

package com.j2se.annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { //定义属性,格式:属性类型+属性名称+括号 String province(); String capital(); } 

2.定义使用MyAnnotation注解的类。

package com.j2se.annotation; import java.util.HashMap; import java.util.Map; //当注解有多个属性时,使用注解时用逗号分隔 @MyAnnotation(province="shanxi",capital="taiyuan") public class MyAnnotationTest { //注解即可以使用在类上,也可以使用在方法上,当类与方法都使用了相同注解时,方法的注解会覆盖类的注解 @MyAnnotation(province="sichuan",capital="chengdu") @SuppressWarnings({ "unchecked", "rawtypes" }) @Deprecated public void output() { System.out.println("Annotation test..."); Map a = new HashMap(); a.put("hello", "world"); } } 

3.自定义注解测试类,通过反射获取注解的属性值以及注解的类型。

package com.j2se.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class MyAnnotationReflect { public static void main(String[] args) throws Exception { MyAnnotationTest test = new MyAnnotationTest(); Class<MyAnnotationTest> myAnnoationTestClass = MyAnnotationTest.class; Method output = myAnnoationTestClass.getMethod("output", new Class[]{}); if(output.isAnnotationPresent(MyAnnotation.class)) { output.invoke(test, new Object[]{}); MyAnnotation myAnnoation = output.getAnnotation(MyAnnotation.class); System.out.println("province : " + myAnnoation.province()); System.out.println("capital : " + myAnnoation.capital()); } Annotation[] annotations = output.getAnnotations(); for(Annotation annotation : annotations) { System.out.println(annotation.annotationType().getName()); } } } 

 

打印结果是:

Annotation test... province : sichuan capital : chengdu com.j2se.annotation.MyAnnotation java.lang.Deprecated 

没有打印出SuppressWarinings,是因为SuppressWarinings的Rentention为source,即不能通过反射读取。

你可能感兴趣的:(exception,String,HashMap,Class,output,Annotations)