Java注解

java注解
注解也叫做元数据,是一种代码级别的说明。注解可以用在
包、类、属性、方法、参数等上面,对源代码的一种标记。

作用:
1.根据注解可以生成文档
2.根据代码中注解的标识可以用反射机制对代码数据的访问
3.通过代码中注解的表示可以让编译器实现对代码的基础检查

实现
声明一个注解通过@interface即可,public @interface custom{}

定义好注解之后需要定义该注解的作用域和生命周期
作用域:该注解应该用在什么地方,如用在方法、属性、包上等
生命周期:该注解保持在什么阶段,如源代码中、编译器中、运行时
三种保持策略
1.SOURCE 保持在源代码中,编译的时候编译器将其忽略
2.CLASS  编译的时候被编译到class文件中,但jvm运行的时候会将其忽略

3.RUMTIME 编译的时候被编译到class文件中,jvm运行的时候还将其保留,因此可以利用反射机制进行获取

代码:
定义一个注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD})
public @interface Custom {


}

@Document 可以生成Java文档
@Target   表示注解的作用域
@Retention 注解的保持策略

可以在注解里定义参数及默认值
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
public @interface Custom {

String name() default "张三";


}
参数相当于声明一个方法,该方法只能声明为public,可以省略

例子:

package core.java.annoation;

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

public class AnnoationTest {
	
	public static void main(String[] args) {
		Class<?> cls = User.class;
		try {
			Field field = cls.getDeclaredField("name");
			Annotation[] annotations = field.getAnnotations();
			for(Annotation annotation : annotations){
				String annoationName = annotation.annotationType().getSimpleName();
				System.out.println("注解名称:" + annoationName);
				Class<?> cl = annotation.annotationType();
				System.out.println("注解类型为:" + cl);
				Custom custom = (Custom)annotation;
				System.out.println("注解的属性值:" + custom.name());
				//获取注解上的方法
				Method[] methods = cl.getMethods();
				for(Method method : methods){
					//获取方法名
					String name = method.getName();
					//获取方法返回值类型
					Class<?> type = method.getReturnType();
					//获取默认返回值
					Object object = method.getDefaultValue();
					System.out.println("注解的方法名:" + name + ",返回值类型:" + type + ",默认返回值:" + object);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

}


package core.java.annoation;

public class User {
	@Custom(name = "李四")
	private String name;

}


package core.java.annoation;

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;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
public @interface Custom {
	
	String name() default "张三";

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值