分享

java反射

 干掉熊猫,我就是国宝 2010-12-24
Java代码
  1. /** 
  2.     * java反射bean的get方法 
  3.     *  
  4.     * @param objectClass 
  5.     * @param fieldName 
  6.     * @return 
  7.     */  
  8.    @SuppressWarnings("unchecked")  
  9.    public static Method getGetMethod(Class objectClass, String fieldName) {  
  10.        StringBuffer sb = new StringBuffer();  
  11.        sb.append("get");  
  12.        sb.append(fieldName.substring(01).toUpperCase());  
  13.        sb.append(fieldName.substring(1));  
  14.        try {  
  15.            return objectClass.getMethod(sb.toString());  
  16.        } catch (Exception e) {  
  17.        }  
  18.        return null;  
  19.    }  

Java代码
  1. /** 
  2.      * java反射bean的set方法 
  3.      *  
  4.      * @param objectClass 
  5.      * @param fieldName 
  6.      * @return 
  7.      */  
  8.     @SuppressWarnings("unchecked")  
  9.     public static Method getSetMethod(Class objectClass, String fieldName) {  
  10.         try {  
  11.             Class[] parameterTypes = new Class[1];  
  12.             Field field = objectClass.getDeclaredField(fieldName);  
  13.             parameterTypes[0] = field.getType();  
  14.             StringBuffer sb = new StringBuffer();  
  15.             sb.append("set");  
  16.             sb.append(fieldName.substring(01).toUpperCase());  
  17.             sb.append(fieldName.substring(1));  
  18.             Method method = objectClass.getMethod(sb.toString(), parameterTypes);  
  19.             return method;  
  20.         } catch (Exception e) {  
  21.             e.printStackTrace();  
  22.         }  
  23.         return null;  
  24.     }  

Java代码
  1. /** 
  2.      * 执行set方法 
  3.      *  
  4.      * @param o 执行对象 
  5.      * @param fieldName 属性 
  6.      * @param value 值 
  7.      */  
  8.     public static void invokeSet(Object o, String fieldName, Object value) {  
  9.         Method method = getSetMethod(o.getClass(), fieldName);  
  10.         try {  
  11.             method.invoke(o, new Object[] { value });  
  12.         } catch (Exception e) {  
  13.             e.printStackTrace();  
  14.         }  
  15.     }  
  16.   
  17.     /** 
  18.      * 执行get方法 
  19.      *  
  20.      * @param o 执行对象 
  21.      * @param fieldName 属性 
  22.      */  
  23.     public static Object invokeGet(Object o, String fieldName) {  
  24.         Method method = getGetMethod(o.getClass(), fieldName);  
  25.         try {  
  26.             return method.invoke(o, new Object[0]);  
  27.         } catch (Exception e) {  
  28.             e.printStackTrace();  
  29.         }  
  30.         return null;  
  31.     } 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多