`
nshg
  • 浏览: 12609 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

自定义注解

    博客分类:
  • JAVA
阅读更多

 

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);
}
…………
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics