Java中常用注解

JDK自带注解
@Override    @Deprecated      @Suppvisewarnings

常见第三方注解:
Spring:@Autried  @Service  @Component  @Repository
Mybatis: @InsertProvider  @UpdateProvider  @Options

注解的分类:
按运行机制分为:
源码注解:只在源码中有,编译成class文件时就没了。
编译时注解:在源码和class文件中都存在。如jdk自带注解。
运行时注解:在运行阶段起作用甚至会影响运行逻辑的注解。如autowired。

元注解:为注解的注解。

自定义注解:
上图中这些注解为元注解,其作用如下描述
@Target(ElementType.METHOD,ElementType.TYPE)
自定义注解作用域定义:其中METHOD为方法上声明,还有CONSTRUCTOR(构造方法声明)、FIELD(字段声明)、LOCAL_VARIABLE(局部变量声明)、PACKAGE(包声明)、PARAMETER(参数声明)、TYPE(类或接口声明)
@Retention(RetentionPolicy.RUNTIME)
自定义生命周期定义:RUNTIME(运行时存在,可通过反射读取)、CLASS(编译时会记录到class中,运行时忽略)、SOURCE(只在源码显示,编译时会丢弃)
@Inherited
自定义注解是否可被子类继承:有该注解表明允许子类继承,且对父类类的注解才有效。它只适用于类继承,接口的实现则无效。(个人灵感:可以通过注解继承实现接口公用参数的校验。)
@Documented
生成javadoc时会包含注解

解析注解:
概念:通过反射获取类、函数或成员上的运行时注解信息,从而实现动态控制程序运行时的逻辑。

代码如下:
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;


@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Decription {
	
	String desc();
	
	String author() default "";
	
	//如果不写默认值,在使用时必须赋值
	int value() default 18;

}<pre name="code" class="java">import java.lang.reflect.Method;

public class ParseAnnoction {
	
	public static void main(String[] args) throws Exception {
		Class clazz = Person.class;
		Decription de = (Decription)clazz.getAnnotation(Decription.class);
		//获得类注解信息
		System.out.println(de.desc() + de.author() + de.value());
		
		Method[] ms = clazz.getMethods();
		for(Method m : ms){
			Decription d = m.getAnnotation(Decription.class);
			if(null != d){
				//获得方法注解信息
				System.out.println(d.author() + d.desc() + d.value());
			}
		}
	}

}

@Decription(author="cao", desc = "hello annocation" )
public class Person {
	
	private String name;
	
	private int age;
	@Decription(desc = "this is getName method")
	public String getName(){
		return this.name;
	}

	public int getAge(){
		return age;
	}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值