java中自定义注解的使用

注解   

   使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。可以通过default来声明参数的默认值。
          定义注解格式:
          public @interface 注解名 {定义体}
        注解参数的可支持数据类型:
            1.所有基本数据类型(int,float,boolean,byte,double,char,long,short)
            2.String类型
            3.Class类型
            4.enum类型
            5.Annotation类型
            6.以上所有类型的数组

  直接上代码:


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;
 
/**
 * 定义一个注解
 */
@Target(ElementType.METHOD) // 这是一个对方法的注解,还可以是包、类、变量等很多东西
@Retention(RetentionPolicy.RUNTIME) // 保留时间,一般注解就是为了框架开发时代替配置文件使用,JVM运行时用反射取参数处理,所以一般都为RUNTIME类型
@Documented // 用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化
public @interface OneAnnotation {
 
	// 定义注解的参数,类型可以为基本类型以及String、Class、enum、数组等,default为默认值
	String parameter1() default "";
	int parameter2() default -1;

使用注解的类

/**
 * 一个用到了自定义的注解的类
 */
public class OneClass {
	
	@OneAnnotation(parameter1="YES", parameter2=10000)
	public void oneMethod () {
	}

提取注解参数


import java.lang.reflect.Method;
 
 
public class TestThis {
 
	public static void main(String[] args) throws Exception {
		// 提取到被注解的方法Method,这里用到了反射的知识
		Method method = Class.forName("OneClass").getDeclaredMethod("oneMethod");
		// 从Method方法中通过方法getAnnotation获得我们设置的注解
		OneAnnotation oneAnnotation = method.getAnnotation(OneAnnotation.class);
		
		// 得到注解的俩参数
		System.out.println(oneAnnotation.parameter1());
		System.out.println(oneAnnotation.parameter2());
	}

测试结果:

YES

10000

猜你喜欢

转载自blog.csdn.net/Kting_Night/article/details/81431661