您的位置:首页 > 编程语言 > Java开发

java 注解

2017-03-16 00:00 267 查看
java 1.5开始有了注解,本质上就是一个标示,用于代码间解耦合
jdk中原生(java原生注解)注解

@Overrride(重写父类中的方法)

@SuppressWarnings(消除警告)

@Deprecate(声明方法已经过时)

元注解,用来修饰描述其他注解(注解的注解)

元注解有4个

@Target //标示注解的作用域(type(类),filed(字段),method(方法)....)

@Retention //标示注解的生命周期 (source(存在于java文件),class(存在于java文件和class文件),runtime(代码运行时也存在,可以影响代码逻辑))

@Documented //标示注解是否可以生成java文档

@Inherited //标示注解是否可以被子类继承

自定义注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Msg {

String default_str = "mgs";

String msg() default default_str;

}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface TableFiled {

String tablefiled ="這個是表裡面沒有的字段";

String getTbaleFiled() default tablefiled;

}

@Msg(msg="this is test")
public class AnnotationTest {

@TableFiled(getTbaleFiled="ceshi---name")
private String name;

@TableFiled(getTbaleFiled="ceshi---age")
private String age;

private String address;

public String getName() {
return name;
}

public String getAge() {
return age;
}

public String getAddress() {
return address;
}

public void setName(String name) {
this.name = name;
}

public void setAge(String age) {
this.age = age;
}

public void setAddress(String address) {
this.address = address;
}

//mian方法简单的解析,真实项目中,会有与注解对应的注解解析器
public static void main(String[] mgs){
AnnotationTest test = new AnnotationTest();
Msg msgs = (Msg)test.getClass().getAnnotation(Msg.class);

System.out.println(msgs.msg());

Field[]  fields =test.getClass().getDeclaredFields();

Arrays.asList(fields).forEach( f ->{
TableFiled tableFiled = f.getAnnotation(TableFiled.class);
if(!StringUtils.isEmpty(tableFiled)){
System.out.println(tableFiled.getTbaleFiled());
}

});
}

}

控制台输出
this is test
ceshi---name
ceshi---age

所有的注解都会默认是 public interface Annotation 接口的子类,就想所有java类都会是Object的子类一样
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java注解