java通过反射获取类信息工具

package cn.pde.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class ReflectUtil {
	public static Map<String,Annotation[]> getFieldNameAndAnnatationsMap(Class clazz) {
		Map<String,Annotation[]> ret = new HashMap<String, Annotation[]>();
		Field[] fields = clazz.getDeclaredFields();
		for(Field field : fields) {
			ret.put(field.getName(), field.getAnnotations());
		}
		return ret;
	}
	
	public static Map<String,Annotation> getFieldNameAndAnnotationMap(Class clazz,Class annoClass) {
		Map<String,Annotation> ret = new HashMap<String, Annotation>();
		Field[] fields = clazz.getDeclaredFields();
		for(Field field : fields) {
			ret.put(field.getName(), field.getAnnotation(annoClass));
		}
		return ret;
	}
	
	public static Annotation getObjAnnotation(Class objClass,Class annoClass) {
		return objClass.getAnnotation(annoClass);
	}
	
	/**
	 * 获取类成员变量相应注解的变量值
	 * eg: ReflectUtil.getAnnoFieldValue(OrgInfo.class, "parent", Column.class, "name") 
	 *  的作用为:获取OrgInfo类中parent变量的@Column注解中的name属性值
	 * @param objClass
	 * @param objFieldName
	 * @param annoClass
	 * @param annoFieldName
	 * @return
	 */
	public static Object getAnnoFieldValue(Class<?> objClass,String objFieldName,Class<?> annoClass, String annoFieldName) {
		Object ret = null;
		Map<String,Annotation> fieldNameAndAnnatationMap = getFieldNameAndAnnotationMap(objClass, annoClass);
		Annotation anno = fieldNameAndAnnatationMap.get(objFieldName);
		if(anno != null) {
			try {
				Method method = annoClass.getMethod(annoFieldName); //Annotation中的成员变量以方法的形式来定义
				ret = method.invoke(anno);
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} 
		}
		return ret;
	}
	
	/**
	 * 获取对象实例中成员变量值(包含父类)
	 * @param obj 对象实例
	 * @param fieldName 变量名
	 * @return
	 */
	public static Object getFieldValue(Object obj, String fieldName) {
		Object ret = null;
		Field field = getField(obj.getClass(), fieldName);
		if(field != null) {
			field.setAccessible(true);
			try {
				ret = field.get(obj);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ret;
	}
	
	/*
	 * 获取类属性(包含父类)
	 */
	public static Field getField(Class<?> clazz, String fieldName) {
		Field ret = null;
		if (clazz != null && !StringUtils.isBlank(fieldName)) {
			try {
				fieldName = fieldName.trim();
				ret = clazz.getDeclaredField(fieldName);
			} catch (Exception e) {//如没找到,则从父类继续查找
				ret = getField(clazz.getSuperclass(), fieldName);
			}
		}
		return ret;
	}

}

你可能感兴趣的:(java)