java注解的使用方法

注解提出的由来:

说起注解,就会想起语文课本里面的注解;实际上,它们的作用是差不多的。就是起一个标示解释作用,它的由来也就清楚了,为了表示一些额外的信息。

注解的定义:

实际上,注解也是一个类,但是有与类有差别。所以,java把注解定义为一个类型type。但是,我们还是可以把它理解为一个类。


注解的种类:

不同的分法,有不同的种类。我就说几种重要的。

一种是按注解的使用位置分,包注解、类注解、属性注解、方法注解、参数注解、局部参数注解、class注解。

一种是按注解的起作用的时机分,source注解、class注解、runtime注解。

一种是按注解使用的对象分,这个可以一般注解和元注解(就是注解的注解,只要带了元这个信息词的意思就是是什么的什么,比如元数据就是数据的数据)

注解的使用方法:

一般使用,使用已经存在的注解:

比如:

public class Main {

	public static void main(String[] args) {
		sayHello();
	}

	@Deprecated
	private static void sayHello(){
		System.out.println("fhajfdhajk");
	}
}

自定义注解:

public @interface AnnotationTest {

}

使用:

	@AnnotationTest
	private static void sayHello2(){
		System.out.println("fhajfdhajk");
	}

使用注解的属性和获取注解、注解的属性

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

@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest {
	String color();
}


@AnnotationTest(color="fahja")
@Deprecated
public class Main {

	public static void main(String[] args) {
		if(Main.class.isAnnotationPresent(AnnotationTest.class)){
			AnnotationTest annotationTest = (AnnotationTest)Main.class.getAnnotation(AnnotationTest.class);
			System.out.println(annotationTest);
			System.out.println(annotationTest.color());
		}
	}

}

注解的特殊属性value,value是可以不用等号就可以赋值的;

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

@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest {
	String color() default "red";
	int value();
}

import java.util.concurrent.Executor;

@AnnotationTest(2)
@Deprecated
public class Main {

	public static void main(String[] args) {
		if(Main.class.isAnnotationPresent(AnnotationTest.class)){
			AnnotationTest annotationTest = (AnnotationTest)Main.class.getAnnotation(AnnotationTest.class);
			System.out.println(annotationTest);
			System.out.println(annotationTest.color());
			System.out.println(annotationTest.value());
		}
	}
}

结果是:

@AnnotationTest(color=red, value=2)
red
2

写的比较好的博客:

http://blog.163.com/nmwx_/blog/static/216219024201312001210996/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值