---
title: "java 自定义注解 "
author: "yaoweinan"
date: "2012-01-30T16:09:34Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-06-04T23:21:56Z"
id: 1384902
url: "https://ilyon.iteye.com/blog/1384902"
---

写道

package com.my;

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

/\**  
\* @author lyon.yao  
\* @date Jan 30, 2012  
\* @function 自定义注解类型  
\*/  
@Retention(RetentionPolicy.RUNTIME)  
public @interface Text {  
boolean isNull() default false;  
String type() default "";  
}

 package com.my;

```
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author lyon.yao
 * @date Jan 30, 2012
 * @function 提取处理注解
 */
public class TestProcess {

	public static void process(String string) {
		// TODO Auto-generated method stub
		try {
			Class clazz = Class.forName(string);
			MyTest myTest=(MyTest) clazz.newInstance();
			Field[] fields =clazz.getFields();
			for(int k=0;k<fields.length;k++){
				Annotation []anns=fields[k].getAnnotations();
				for (int i = 0; i < anns.length; i++) {
					Text text=(Text) anns[i];
					if(myTest.a==null){
						System.out.println(text.isNull());
					}
					System.out.print(text.type());
				}
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
```

 package com.my;

```
/**
 * @author lyon.yao
 * @date Jan 30, 2012
 * @function 测试类
 */
public class MyTest {

	/**
	 * @param args
	 */
	@Text(isNull=false,type="Integer")
	public Integer a=1;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestProcess.process("com.my.MyTest");
	}

}
```