java 获取属性值和设置属性值

java 获取属性值和设置属性值
/**
     * 获取属性值
     * @param obj
     * @param property
     * @return
     */
    public static Object getObjProVal(Object obj, String property) {
        Object val = null;
        int len = property.length();
        String methodName = "get" + property.substring(0, 1).toUpperCase() + property.substring(1, len);
        try {
            Method method = obj.getClass().getMethod(methodName);
            val = method.invoke(obj);
        } catch (Exception e) {
        }
        return val;
    }
    
    /**
     * 设置属性值
     * @param obj
     * @param property
     * @param value
     * @return
     */
    public static void setObjProVal(Object obj, String property, Object value) {
        int len = property.length();
        String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1, len);
        try {
            Method method = obj.getClass().getMethod(methodName, value.getClass());
            method.invoke(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18483

发表评论