java 利用反射读取注解功能

package com.lideng.annotation;

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

/**
 * 使用反射读取注解信息
 * @author Administrator
 *
 */
public class Demo02 {

	public static void main(String[] args) {
		
		try {
			Class clazz = Class.forName("com.lideng.annotation.User");
			//获得类的所有注解
			Annotation[] annotations = clazz.getAnnotations();
			for (Annotation a : annotations) {
				System.out.println(a);
			}
			//获得指定类的注解
			UserAnnotation us =(UserAnnotation) clazz.getAnnotation(UserAnnotation.class);
			System.out.println(us.value());
			
			//获得类的属性注解
			Field f = clazz.getDeclaredField("userName");
			MyField userField = f.getAnnotation(MyField.class);
			System.out.println(userField.columnName()+"---"+userField.type()+"---"+userField.lenght());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

  

猜你喜欢

转载自www.cnblogs.com/qurui1997/p/10609899.html