反射方法总结

来源:互联网 发布:苏大成教网络教学平台 编辑:程序博客网 时间:2024/06/07 10:02

package com.hyd.common.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import com.hyd.common.util.MyBeanUtils;

public class MyBeanUtils {
 protected static Logger logger = LoggerFactory.getLogger(MyBeanUtils.class);

 /**
  * 获得同时有get和set的field和value。
  *
  * @param bean
  * @return
  */
 @SuppressWarnings("unchecked")
 public static Map describe(Object bean) {
  Map des = new HashMap();
  PropertyDescriptor desor[] = PropertyUtils.getPropertyDescriptors(bean);
  String name = null;
  for (int i = 0; i < desor.length; i++) {
   if (desor[i].getReadMethod() != null
     && desor[i].getWriteMethod() != null) {
    name = desor[i].getName();
    try {
     des.put(name, PropertyUtils.getProperty(bean, name));
    } catch (Exception e) {
     throw new RuntimeException("属性不存在:" + name);
    }
   }
  }
  return des;
 }

 public static void setSimpleProperty(Object bean, String name, Object value) {
  try {
   PropertyUtils.setSimpleProperty(bean, name, value);
  } catch (Exception e) {
   throw new RuntimeException("属性不存在:" + name);
  }
 }

 public static Object setSimpleProperty(Object bean, String name) {
  try {
   return PropertyUtils.getSimpleProperty(bean, name);
  } catch (Exception e) {
   throw new RuntimeException("属性不存在:" + name);
  }
 }

 /**
  * 直接读取对象属性值,无视private/protected修饰符,不经过getter函数.
  */
 public static Object getFieldValue(Object object, String fieldName)
   throws NoSuchFieldException {
  Field field = getDeclaredField(object, fieldName);
  if (!field.isAccessible()) {
   field.setAccessible(true);
  }

  Object result = null;
  try {
   result = field.get(object);
  } catch (IllegalAccessException e) {
   logger.error("不可能抛出的异常{}", e.getMessage());
  }
  return result;
 }

曾自桃-研发一部 2013-03-29 14:42:46
public static void main(String[] args) {
  Test test = new Test();
  test.setT1("ddd");
  Field[] fs = test.getClass().getDeclaredFields();
  
  try {
   String result = (String) MethodUtils.invokeMethod(test, "getT1", null);
   MethodUtils.invokeMethod(test, "setT1", "eee");
   result = (String) MethodUtils.invokeMethod(test, "getT1", null);
   System.out.println(result);
  } catch (NoSuchMethodException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  for(Field f : fs){
   String attribute = f.getName();
   String method = "get" + attribute.substring(0, 1).toUpperCase() + attribute.substring(1, attribute.length());
   System.out.println(attribute + "," + method);
  }
 }

 


 /**
  * 直接设置对象属性值,无视private/protected修饰符,不经过setter函数.
  */
 public static void setFieldValue(Object object, String fieldName,
   Object value) throws NoSuchFieldException {
  Field field = getDeclaredField(object, fieldName);
  if (!field.isAccessible()) {
   field.setAccessible(true);
  }
  try {
   field.set(object, value);
  } catch (IllegalAccessException e) {
   logger.error("不可能抛出的异常:{}", e.getMessage());
  }
 }

 /**
  * 循环向上转型,获取对象的DeclaredField.
  */
 public static Field getDeclaredField(Object object, String fieldName)
   throws NoSuchFieldException {
  Assert.notNull(object);
  return getDeclaredField(object.getClass(), fieldName);
 }

 /**
  * 循环向上转型,获取类的DeclaredField.
  */
 @SuppressWarnings("unchecked")
 public static Field getDeclaredField(Class clazz, String fieldName)
   throws NoSuchFieldException {
  Assert.notNull(clazz);
  Assert.hasText(fieldName);
  for (Class superClass = clazz; superClass != Object.class; superClass = superClass
    .getSuperclass()) {
   try {
    return superClass.getDeclaredField(fieldName);
   } catch (NoSuchFieldException e) {
    // Field不在当前类定义,继续向上转型
   }
  }
  throw new NoSuchFieldException("No such field: " + clazz.getName()
    + '.' + fieldName);
 }
}

原创粉丝点击