javaSE注解的学习

2014-11-24 07:53:49 · 作者: · 浏览: 0

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})//这个注解放的位置,方法和type
public @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 {
	@Deprecated
	public 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();
}	

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