Java 之注解浅谈


package com.enhance.Annotaion;

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

import com.enhance.enumeration.TrafficLamp;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyAnnotation {

//如果这个注解只有一个value属性,那么在使用注解的时候前面的value=可以省略
String value();

//如果这个注解有 默认的值,那么在使用注解的时候可以不用赋值.否则 必须赋值
String color() default "blue";

int[] arrayAttr() default {3,4,4};

TrafficLamp lamp() default TrafficLamp.RED;

MetaAnnotaion annotationAtrr() default @MetaAnnotaion("hibernate");

Class classAttr() default MyAnnotation.class;
}


原注解

package com.enhance.Annotaion;

public @interface MetaAnnotaion {
String value();
}



package com.enhance.Annotaion;

import java.util.Arrays;

import com.enhance.enumeration.TrafficLamp;

@MyAnnotation(annotationAtrr=@MetaAnnotaion("Spring"),color="yellow",value="abc",arrayAttr=4,lamp=TrafficLamp.YELLOW) //如果数组属性的值只有一个,可以省略 {}
//@MyAnnotation(color="yellow",value="abc",arrayAttr={1,2,3}) //一点加入了标注,就表示创建了这个类的对象
public class AnnotationTest {

@MyAnnotation("money") //这里是给 value属性赋值
public static void main(String[] args){
//对应用注解的类,使用反射进行操作
if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){
//如果这个类中存在这个注解 就进行 相应的操作
MyAnnotation annotation=(MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class);
System.out.println(annotation.color()); //yellow
System.out.println(annotation.value()); //abc
System.out.println(Arrays.toString(annotation.arrayAttr())); //给数组复制
System.out.println(annotation.lamp().nextLamp().name());
System.out.println(annotation.annotationAtrr().value());
}
}
}



//说明

十、 注解
a) @ SuppressWarnings(“deprecation”):禁止显示警告
b) @Deprecated:让某个方法过时
c) @Override:重写的时候最好加上
d) 注解标记可以加在 包,类,字段,方法,方法的参数,局部变量上.
e) 注解的应用
i. 定义注解类 public @interface MyAnnotation
ii. 应用注解类 @MyAnnotation
iii. 对应用注解类的类进行反射操作的类
f) @Retention(RetentionPolicy.RUNTIME):定义注解类的生命周期Source,Class,Runtime
g) @Target({ElementType.METHOD,ElementType.TYPE}):标记我们的注解可以应用的在那些成员上(Type: class)
h) 给自定义注解加如属性
i. 可以省略名称的 value()
ii. 定义简单类型属性 String ;如果 可选设置的话,必须加上 缺省default 值
iii. 定义 数组属性 int[] arrayAttr;如果只有一个值的时候,可以省略{}
iv. 定义 枚举类型的数组 TrafficLamp [] lamp() default TrafficLamp.RED;
v. 定义 注解类型的的属性
vi. 定义 Class 类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值