自定义注解

 

1、自定义注解步骤:

※ 继承java.annotation.Annotation接口

※ 标注注解的生存周期

※ 定义注解的属性以及缺省值

※ 定义注解类处理类,负责处理注解

 

 

注解类定义如下:

 

package com.nshg.annotation

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
	String type() default “varchar”;
}

 

 

说明:

◆标记@Retention定义注解的生存周期,其取值范围如下

  RetentionPolicy.CLASS 保留到编译期,加载类的时候不生效

  RetentionPolicy.SOURCE 保留在源代码期间,编译后的class不保留

  RetentionPolicy.RUNTIME 保留到运行期间,编译后的class保留,可通过反射获取注解信息

◆标记@interface表明这是一个继承与java.annotation.Annotation的注解类

type()表明MyAnnotation注解中包含类型为stringtype属性,其缺省值为varchar

@Target代表注解修饰范围,属于java.lang.annotation.ElementType,值可取

TYPE 可以修饰类、接口、枚举、注解 

FIELD 可以修饰成员变量

METHOD 可以修饰方法

PARAMETER 可以修饰参数

CONSTRUCTOR 可以修饰构造方法

LOCAL_VARIABLE 可以修饰局部变量

ANNOTATION_TYPE 可以修饰Annotation

PACKAGE 可以修饰包

 

 

定义注解类处理类如下:

 

 

page com.nshg.annotation

import java.lang.annotation.Annotation;
import java.refect.Filed;

public MyAnnotationProcess {
	public static process(Object obj) throws ClassNotFoundException {
		//获取所有注解
		Annotation[] annotations = obj.getClass().getAnnotations();
		Filed[] fileds = obj.getClass().getDeclaredFileds();

		for(Annotation annotation : annotations) {
			if (annotation instanceof XXX) {
				XXX annot = (XXX)annotation;
                        }
		}

		for (Filed filed : fileds) {
			Annotation[] filedAnnotations = filed.getAnnotations();
			for (Annotation filedAnnotation : filedAnnotations) {
				if (filedAnnotation instanceof YYY) {
					YYY	yyy = (YYY) filedAnnotation;
                                }
                        }
                 }
         }
}
 

 

 

 DAO类写法如下:

 

………
Public void save(XXX xxx) throws ClassNotFoundException {
	MyAnnotationProcess. Process(xxx);
}
…………
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值