Java 自定义注解(Annotation)

在上一篇文章中介绍了注解的原理和适用场景,这一篇开始如何自定义Annotation。

Annotation是不同于Class、Interface、Enum,使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。



1、自定义MyAnnotation

package com.example.annotation;

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

//@Target({ElementType.METHOD})
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	String name() default "abc";	//指定 默认值
	int age();
	float[] grade();
}


@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型。可以通过default来声明参数的默认值。方法返回值类型必须为primitive(8种基本数据类型)类型、Class类型、枚举类型、Annotation类型或者由前面任意类型之一的一维数组。在这里可以看到@Retention和@Target这样的元注解,用来声明注解本身的行为。@Retention用来声明注解的保留策略,有CLASS、RUNTIME和SOURCE这三种,分别表示注解保存在类文件、JVM运行时刻和源代码中。只有当声明为RUNTIME的时候,才能够在运行时刻通过反射API来获取到注解的信息。@Target用来声明注解可以被添加在哪些类型的元素上,如类型、方法和域等。


注意:注解是不能继承的


2、使用MyAnnotation

@MyAnnotation(name="aaa",age=24,grade={84.5f,90.0f})
	public boolean isPermitted(){
		
		return false;
	}


3、利用反射获取注解的属性值

package com.example.annotation;

import java.lang.reflect.Method;
import java.sql.Connection;

public class JdbcUtils {

	public static void main(String[] args) {
		getConnection();
	}
	
	@DbInfo(driver="com.mysql.jdbc.Driver",url="jdbc:mysql:///test",user="root",password="root")
	public static Connection getConnection(){
		
//		Class clazz = JdbcUtils.class;
		try {
			Class clazz = Class.forName("com.example.annotation.JdbcUtils");
			
			//方法1
			Method[] methods = clazz.getMethods();
			for (Method method : methods) {
                if(method.isAnnotationPresent(DbInfo.class)){	//判断该方法上是否有DbInfo注解
                	DbInfo info = (DbInfo)method.getAnnotation(DbInfo.class);
                    
                	System.out.println("Method["+method.getName()+"],driver["+info.driver()+"],url["+info.url()+"],user["+info.user()+"],password["+info.password()+"]");
                }
			}
			
			//方法2
			Method method = clazz.getMethod("getConnection", null);
			DbInfo dbInfo = method.getAnnotation(DbInfo.class);
			
			if(dbInfo!=null){
				System.out.println("Method["+method.getName()+"],driver["+dbInfo.driver()+"],url["+dbInfo.url()+"],user["+dbInfo.user()+"],password["+dbInfo.password()+"]");
			}
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值