Java Annotation

1.Annotation简介:

          Annotation提供一种机制,将程序中元素(如类、方法、属性等)和元数据联系起来。这样编译器可以将元数据保存的class文件中。代码分析工具就可以使用这些元数据执行的额外任务。注释采用“at”标记形式 ( @ ),后面是注释名称。

AnnotationDubug.java

package annotation.test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * annotation 提供一种机制,将程序中元素(如类、方法、属性等)和元数据联系起来。
 * 这样编辑器可以将元数据保存在class文件中。
 * 代码分析工具就可以使用这些元数据执行额外任务。注释采用"at"标记心事(@at),后面是注释名称
 * @author 我的账号
 *
 */

/**
 * annotation 类型是一种接口,能够通过java反射API的方式提供对信息的访问
 *
 */

/**
 * Documented 产生java Doc文件,这次可以看到文件包括了@Debug 的信息
 */
@Documented


@Target({ElementType.CONSTRUCTOR,ElementType.METHOD})	//指定目标

@Retention(RetentionPolicy.RUNTIME)	//设置保持性

@Inherited
public @interface AnnotationDebug {
    //定义了value()方法,编译器在编译时会自动帮您产生一个value的变量成员,接着在使用Debug Annotation时要指定值
    //注释类型的数据成员被设置成使用有限信息进行工作
    //定义数据成员不需要分别定义访问和修改的方法,只需定义一个方法,以数据成员的名称命名它,数据类型应该是该方法返回值的类型.
    String value()default "windfree";//默认值的类型必需与成员变量的申明类型一置
    String name();
}



/**
 * java 标准的Annotation
 * @Deprecated 相当于Javadoc的@deprecated,被@Deprecated标注的对象class,method等被注明为不推荐使用。
 * @Override 注明对象method重载类父类的方法.Javac等工具编译时会根据此Annotation判断重载方法是否正确
 * @SuppressWarning 告诉Javac等编译器忽略所指定的特定的警告信息
 * @Target被定义的annotation可以附加到那些对象上
 * @Retention annotation的作用于间
 * @author 我的账号
 *
 */

在程序中使用自定义的annotation
TestDebug.java

package annotation.test;
/**
 * 自定义的annotation
 * @author 我的账号
 */
public class TestDebug {
	@AnnotationDebug(
			name = "zgliu"
		)
	public void doSomething(){}
}	
DebugTool.java

package annotation.test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 使用java反射API读取class中的源数据的信息
 *
 */
public class DebugTool {
	public static void main(String[] args) throws SecurityException, NoSuchMethodException {
		Class<TestDebug> c = TestDebug.class;
		Method method = c.getMethod("doSomething");
		if(method.isAnnotationPresent(AnnotationDebug.class)){
			System.out.println("@Debug is found");
		
			AnnotationDebug debug = method.getAnnotation(AnnotationDebug.class);
			System.out.println("tvalue =" + debug.value());
			System.out.println("tname =" + debug.name());
		}else{
			System.out.println("@Debug is not found");
		}
		
		Annotation[] annotations = method.getAnnotations();
		for (Annotation annotation : annotations) {
			System.out.println(
						annotation.annotationType().getName()
					);
		}
	}
}

完.



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值