注解总结


注解(Annotation

 

注解:是JDK1.5的新特性。相当于一种标记,在程序上加了它就等于为程序打上了某种标记,以后java编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有无何种标记,以便于进行下一步相应的操作。

标记可以加在包、类、方法、字段、方法的参数以及局部变量上。

 

几个基本的注解:

1、@SuppressWarnings(“deprecation) //压缩警告,告诉编译器不再提示方法过时。

2、@Deprecated //标记过时,例如标记以下方法已过时了,其他程序调用就会提示此为过时方法。

3、@Override //标记子类复写的父类的某个方法。(可以用来检测是否写正确,不正确的话,覆盖父类方法失败)。

 

关于注解的问题及理解:

由于编译完源文件后会去掉一部分注解,用类加载器加载class文件进内存后变成的二进制数据才是字节码文件,而编译器拿到的是二进制的字节码,所以会产生明明加了注解但利用反射技术却得不到该类身上的注解。

注解的存在位置(不准确)分为三部分:java源文件——>class文件——>内存中的字节码。

分别对应三种取值:RetentionPolicy.SOURCERetentionPolicy.CLASSRetentionPolicy.RUNTIME

 

自定义注解及在注解上添加相应的属性信息:

 

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;


//添加自定义注解
@MyAnnotationForTest(classAttr=String.class,annotationAttr=@MyMetaAnnotation("itheima"),color="green",value="cyx",arrayAttr={1,3})
public class MyAnnotationTest
{
	private String string = "abc";
	
	//基本注解之一:标记方法已过时
	@Deprecated
	public static void printString(String string)
	{
		System.out.println(string);
	}
	//基本注解之二:子类复写父类方法
	@Override
	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + ((string == null) ? 0 : string.hashCode());
		return result;
	}

	//基本注解之三:压缩警告,不再提示方法过时
	@SuppressWarnings("deprecation")
	public static void main(String[] args)
	{
		System.runFinalizersOnExit(true);
		String string = "12345";
		printString(string);
		
		//判断MyAnnotationTest类中是否有MyAnnotationForTest类型的注解。
		if(MyAnnotationTest.class.isAnnotationPresent(MyAnnotationForTest.class))
		{
			//通过反射技术,获得MyAnnotationForTest类型注解,并操作注解内的属性。
			MyAnnotationForTest annotationForTest = 
					(MyAnnotationForTest)MyAnnotationTest.class.getAnnotation(MyAnnotationForTest.class);
			System.out.println(annotationForTest.color());
			System.out.println(annotationForTest.value());
			System.out.println(annotationForTest.arrayAttr().length);
			System.out.println(annotationForTest.classAttr().getName());
			System.out.println(annotationForTest.annotationAttr().value());
		}
	}
	
}


//让注解信息保留到运行时期。
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotationForTest
{
	String color() default "yellow";//对属性添加缺省值
	String value();
	int[] arrayAttr();//数组类型
	Class<?> classAttr();//Class类型
	//@MyMetaAnnotation代表MyMetaAnnotation的一个实例对象
	MyMetaAnnotation annotationAttr() default @MyMetaAnnotation("heima");//注解类型
}

public @interface MyMetaAnnotation
{
	String value();
}


运行结果:
12345
green
cyx
2
java.lang.String
itheima


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值