javaSE注解的学习

来源:互联网 发布:上海 网络信息安全员证 编辑:程序博客网 时间:2024/06/02 23:27

javase是基础,注解在我们java学习道路中是很常见的,在座web开发的时候就会用到。

注解的使用方便了我们开发。



下面就简单演示下注解的定义和对注解中德属性进行赋值并取出来。


创建注解类:(MyAnntation)

package com.ydcun.day2;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import com.ydcun.test;@Retention(RetentionPolicy.RUNTIME)//注解保留到什么时候@Target({ElementType.METHOD,ElementType.TYPE})//这个注解放的位置,方法和typepublic @interface InMyAnnotation {String b() default "aa";int[] arr();String value();//单独的时候赋值可以不指定名称test.TrefficLamp lamp() default test.TrefficLamp.RED;//用枚举类型Elment elment();//用注解类型}

创建一个类来使用这个注解

package com.ydcun.day2;import javax.annotation.security.RolesAllowed;import javax.ejb.Remote;import com.sun.xml.internal.bind.v2.schemagen.xmlschema.Annotated;@InMyAnnotation(arr=1,value = "ddd",elment = @Elment("ydcun"))public class ZJ {@Deprecatedpublic void S(){}@SuppressWarnings("deprecation")//过时的继续用public static void main(String[] args) {System.runFinalizersOnExit(true);//这个是过时的if(ZJ.class.isAnnotationPresent(InMyAnnotation.class)){InMyAnnotation inMyAnnotation = ZJ.class.getAnnotation(InMyAnnotation.class);//获取到注解,与注解的生命周期有关System.out.println(inMyAnnotation);System.out.println(inMyAnnotation.arr().length);System.out.println(inMyAnnotation.b());System.out.println(inMyAnnotation.value());System.out.println(inMyAnnotation.lamp().nextLamp().name());System.out.println(inMyAnnotation.elment().value());}}}

上面最后一个注解型的属性类型定义如下:(Elment)


package com.ydcun.day2;public @interface Elment {String value();}

注解这只是定义和给属性复制,后续会有深入应用









0 0