首页 > 代码库 > JAVA注解入门
JAVA注解入门
package testannotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.Field;import java.lang.reflect.Method;/** * @Target说明了Annotation所修饰的对象范围 * @Retention定义了该Annotation被保留的时间长短 * @Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API */@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@interface TypeAnnotation { String value() default "DefaultTypeAnnotation";}@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@interface MethodAnnotation { String name() default "Default Annotation Name"; String url() default "default.com";}@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)@interface FieldAnnotation { String value() default "DefaultFieldAnnotation";}@TypeAnnotation("Test the use of TypeAnnotation")class UseAnnotion { @FieldAnnotation(value="FieldAnnotation with value") private String field; @FieldAnnotation private String fieldWithDefault; @MethodAnnotation() public void testMethodAnnotation() { System.out.println("UseAnnotion->testMethodAnnotation"); } @MethodAnnotation(name="唯品会",url="vip.com") public void testMethodAnnotationWithValue() { System.out.println("UseAnnotion->testMethodAnnotationWithValue"); }}public class TestAnnotation { public static void main(String[] args) throws ClassNotFoundException { Class anno = Class.forName("testannotation.UseAnnotion"); Method[] method = anno.getMethods(); boolean flag = anno.isAnnotationPresent(TypeAnnotation.class); if (flag) { TypeAnnotation first = (TypeAnnotation) anno.getAnnotation(TypeAnnotation.class); System.out.println("类型注解值:" + first.value()); } for (Method m : method) { MethodAnnotation methodAnno = m .getAnnotation(MethodAnnotation.class); if (methodAnno == null) continue; System.out.println("获取方法注解\nname:\t" + methodAnno.name() + "\nurl:\t" + methodAnno.url()); } Field []field = anno.getDeclaredFields(); for(Field f : field) { FieldAnnotation fieldAnnotation = (FieldAnnotation)f.getAnnotation(FieldAnnotation.class); System.out.println("获取域注解:"+fieldAnnotation.value()); } }}
JAVA注解入门
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。