當前位置: 首頁>>代碼示例>>Java>>正文


Java ConvertUtils類代碼示例

本文整理匯總了Java中org.apache.commons.beanutils.ConvertUtils的典型用法代碼示例。如果您正苦於以下問題:Java ConvertUtils類的具體用法?Java ConvertUtils怎麽用?Java ConvertUtils使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ConvertUtils類屬於org.apache.commons.beanutils包,在下文中一共展示了ConvertUtils類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: mapToBean

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
/**
 * map to bean
 * 轉換過程中,由於屬性的類型不同,需要分別轉換。
 * java 反射機製,轉換過程中屬性的類型默認都是 String 類型,否則會拋出異常,而 BeanUtils 項目,做了大量轉換工作,比 java 反射機製好用
 * BeanUtils 的 populate 方法,對 Date 屬性轉換,支持不好,需要自己編寫轉換器
 *
 * @param map  待轉換的 map
 * @param bean 滿足 bean 格式,且需要有無參的構造方法; bean 屬性的名字應該和 map 的 key 相同
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private static void mapToBean(Map<String, Object> map, Object bean) throws IllegalAccessException, InvocationTargetException {

    //注冊幾個轉換器
    ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
    ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class);
    //注冊一個類型轉換器  解決 common-beanutils 為 Date 類型賦值問題
    ConvertUtils.register(new Converter() {
        //  @Override
        public Object convert(Class type, Object value) { // type : 目前所遇到的數據類型。  value :目前參數的值。
            // System.out.println(String.format("value = %s", value));

            if (value == null || value.equals("") || value.equals("null"))
                return null;
            Date date = null;
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = dateFormat.parse((String) value);
            } catch (Exception e) {

                e.printStackTrace();
            }

            return date;
        }

    }, Date.class);

    BeanUtils.populate(bean, map);
}
 
開發者ID:h819,項目名稱:spring-boot,代碼行數:41,代碼來源:MyBeanUtils.java

示例2: check

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
public static void check()
{
  if (classLoaders.putIfAbsent(Thread.currentThread().getContextClassLoader(), Boolean.TRUE) == null) {
    loadDefaultConverters();
    for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) {
      try {
        final StringCodec<?> codecInstance = entry.getValue().newInstance();
        ConvertUtils.register(new Converter()
        {
          @Override
          public Object convert(Class type, Object value)
          {
            return value == null ? null : codecInstance.fromString(value.toString());
          }

        }, entry.getKey());
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
  }
}
 
開發者ID:apache,項目名稱:apex-core,代碼行數:23,代碼來源:StringCodecs.java

示例3: convertToString

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
public String[] convertToString(Object[] objects) {
    String[] strings = new String[objects.length];

    int i = 0;
    for (Object object : objects) {
        if (object != null) {
            Converter converter = ConvertUtils.lookup(object.getClass());
            if (converter != null) {
                strings[i++] = converter.convert(object.getClass(), object).toString();
            } else {
                strings[i++] = object.toString();
            }
        } else {
            strings[i++] = "";
        }
    }

    return strings;
}
 
開發者ID:maxdelo77,項目名稱:replyit-master-3.2-final,代碼行數:20,代碼來源:CsvExporter.java

示例4: set

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
/**
 * Set the value of a simple property with the specified name.
 *
 * @param name Name of the property whose value is to be set
 * @param value Value to which this property is to be set
*/
public void set(String name, Object value) {

    // Set the page number (for validator)
    if ("page".equals(name)) {

        if (value == null) {
            page = 0;
        } else  if (value instanceof Integer) {
            page = ((Integer)value).intValue();
        } else {
            try {
                page = ((Integer)ConvertUtils.convert(value.toString(), Integer.class)).intValue();
            }
            catch (Exception ignore) {
                page = 0;
            }
        }
    }

    dynaBean.set(name, value);

}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:29,代碼來源:BeanValidatorForm.java

示例5: convertToObject

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
/**
	 * 基於Apache BeanUtils轉換字符串到相應類型.
	 * 
	 * @param value 待轉換的字符串.
	 * @param toType 轉換目標類型.
	 */
	public static Object convertToObject(String value, Class<?> toType) {
		Object cvt_value=null;
		try {
				cvt_value=ConvertUtils.convert(value, toType);	
//			if(toType==Date.class){
//				System.out.println("0----0");
//				SimpleDateFormat dateFormat=null;
//				try{
//					dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//					cvt_value=dateFormat.parse(value);	
//				}catch(Exception e){
//					dateFormat=new SimpleDateFormat("yyyy-MM-dd");
//					cvt_value=dateFormat.parse(value);	
//				}
//			}
		} catch (Exception e) {
			throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
		}
		return cvt_value;
	}
 
開發者ID:wkeyuan,項目名稱:DWSurvey,代碼行數:27,代碼來源:ObjectMapper.java

示例6: entity2Dto

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
private static void entity2Dto() {
	EUser u = new EUser();
	u.setId(1l);
	u.setUsername("yoking");
	u.setCreationDate(new Date(System.currentTimeMillis()));
	
	UserDTO user = new UserDTO();
	
	ConvertUtils.register(new DateStringConverter(), String.class);
	try {
		BeanUtils.copyProperties(user, u);
	} catch (IllegalAccessException | InvocationTargetException e) {
		e.printStackTrace();
	}
	
	System.out.println(user);
}
 
開發者ID:yoking-zhang,項目名稱:demo,代碼行數:18,代碼來源:ConverterApp.java

示例7: dto2Entity

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
private static void dto2Entity() {
	UserDTO user = new UserDTO();
	user.setId(1l);
	user.setUsername("joking");
	user.setCreationDate("2016-04-20");
	
	EUser u = new EUser();
	ConvertUtils.register(new DateStringConverter(), Date.class);
	try {
		BeanUtils.copyProperties(u, user);
	} catch (IllegalAccessException | InvocationTargetException e) {
		e.printStackTrace();
	}
	
	System.out.println(u);
}
 
開發者ID:yoking-zhang,項目名稱:demo,代碼行數:17,代碼來源:ConverterApp.java

示例8: toValue

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
private static Object toValue(String initial, Class clazz) {
    Object value;
    try {
        if (initial != null) {
            value = ConvertUtils.convert(initial, clazz);
        } else {
            if (clazz.isArray()) {
                value = Array.newInstance(clazz.getComponentType(), 0);
            } else {
                value = clazz.newInstance();
            }
        }
    } catch (Throwable t) {
        log.warn("No es pot convertir '" + initial + "' a " + clazz.getName());
        value = null;
    }
    return (value);
}
 
開發者ID:GovernIB,項目名稱:sistra,代碼行數:19,代碼來源:PantallaUtils.java

示例9: getList

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
@Override
public <T> List<T> getList(Object aKey, Class<T> aElementType) {
  List list = get(aKey, List.class);
  if(list == null) {
    return null;
  }
  List<T> typedList = new ArrayList<>();
  for(Object item : list) {
    if(aElementType.equals(Accessor.class) || aElementType.equals(MapObject.class)) {
      typedList.add((T)new MapObject((Map<String, Object>) item));
    }
    else {
      typedList.add((T)ConvertUtils.convert(item,aElementType));
    }
  }
  return Collections.unmodifiableList(typedList);
}
 
開發者ID:creactiviti,項目名稱:piper,代碼行數:18,代碼來源:MapObject.java

示例10: getVariableMap

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
@JsonIgnore
public Map<String, Object> getVariableMap() {

	ConvertUtils.register(new DateConverter(), java.util.Date.class);

	if (StringUtils.isBlank(keys)) {
		return map;
	}

	String[] arrayKey = keys.split(",");
	String[] arrayValue = values.split(",");
	String[] arrayType = types.split(",");
	for (int i = 0; i < arrayKey.length; i++) {
		String key = arrayKey[i];
		String value = arrayValue[i];
		String type = arrayType[i];

		Class<?> targetType = Enum.valueOf(PropertyType.class, type).getValue();
		Object objectValue = ConvertUtils.convert(value, targetType);
		map.put(key, objectValue);
	}
	return map;
}
 
開發者ID:EleTeam,項目名稱:Shop-for-JavaWeb,代碼行數:24,代碼來源:Variable.java

示例11: set

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
/**
 * Set the value of a simple property with the specified name.
 *
 * @param name  Name of the property whose value is to be set
 * @param value Value to which this property is to be set
 */
public void set(String name, Object value) {
    // Set the page number (for validator)
    if ("page".equals(name)) {
        if (value == null) {
            page = 0;
        } else if (value instanceof Integer) {
            page = ((Integer) value).intValue();
        } else {
            try {
                page =
                    ((Integer) ConvertUtils.convert(value.toString(),
                        Integer.class)).intValue();
            } catch (Exception ignore) {
                page = 0;
            }
        }
    }

    dynaBean.set(name, value);
}
 
開發者ID:SonarSource,項目名稱:sonar-scanner-maven,代碼行數:27,代碼來源:BeanValidatorForm.java

示例12: fastPopulate

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
/**
 * 將Map的值裝入指定的對象中
 *
 * @param obj        對象
 * @param properties map值
 * @throws java.lang.reflect.InvocationTargetException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
public static void fastPopulate(Object obj, Map<String, Object> properties) {
    Class<?> classz = obj.getClass();
    Map<String, PropertiesEntry> map = getFastBeanCache().getPropertiesEntryMap(classz);
    if (map.size() > 0) {
        try {
            for (Map.Entry<String, Object> entry : properties.entrySet()) {

                PropertiesEntry pe = map.get(entry.getKey());
                if (pe != null) {
                    if (pe.getSet() != null) {
                        if (entry.getValue() != null) {
                            Object v = ConvertUtils.convert(entry.getValue(), pe.getType());
                            pe.getSet().invoke(obj, v);
                        } else {
                            entry.setValue(null);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
 
開發者ID:treeleafj,項目名稱:treeleaf,代碼行數:34,代碼來源:FastBeanUtils.java

示例13: test4

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
@Test
public void test4() throws Exception{
	String name="aaa";
	String password="123";
	String age="24";
	String birthday="1980-09-09";
	
	//ʹ��apache���Ѿ�ʵ��Convert�ӿڵ�ת������DateLocaleConverterʵ�ֽ�ǰ�˷��͵��������͵��ַ�������ת��Ϊbean�������Ե�������������
	ConvertUtils.register(new DateLocaleConverter(), Date.class);
	
	Person bean=new Person();
	BeanUtils.setProperty(bean, "name", name);//��ʾ�����ĸ�bean���ĸ����ԣ���Ϊ������Ը�ֵΪvalue
	BeanUtils.setProperty(bean, "password", password);
	BeanUtils.setProperty(bean, "age", age);//ֻ֧���ַ�����8�ֻ������������Զ�ת��
	BeanUtils.setProperty(bean, "birthday", birthday);
	
	System.out.println(bean.getName());//aaa
	System.out.println(bean.getPassword());//123
	System.out.println(bean.getAge());//24�����Կ���ǰ̨���ݹ������ݶ������ַ������͵ģ�����bean����age������int�ͣ�Ҳ����beanUtils���֧�ֽ�ǰ̨���ַ��������Զ�ת��Ϊ���ֻ����������ݣ����Ǹ������ͣ��Ͳ������ˣ���Ҫ����Ϊ��������ע��һ��ת��������beanUtils�����ת����ȥ��ǰ̨string����ת��Ϊbean����ĸ����������ԣ�����������
	System.out.println(bean.getBirthday().toLocaleString());//1980-9-9 0:00:00
}
 
開發者ID:mushroomgithub,項目名稱:ServletStudyDemo,代碼行數:22,代碼來源:Demo1.java

示例14: test5

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
@Test
public void test5() throws Exception{
	Map map=new HashMap();
	map.put("name", "aaa");
	map.put("password", "123");
	map.put("age", "23");
	map.put("birthday", "1980-09-09");
	
	//ʹ��apache���Ѿ�ʵ��Convert�ӿڵ�ת������DateLocaleConverterʵ�ֽ�ǰ�˷��͵��������͵��ַ�������ת��Ϊbean�������Ե�������������
	ConvertUtils.register(new DateLocaleConverter(), Date.class);
	Person bean =new Person();
	BeanUtils.populate(bean, map);//ʹ��map���ϵ�key-valueֵ���bean��������ԣ��ڲ��ǽ�map�ؼ���keyΪname������valueֵ��䵽bean�����Ӧ��name����ֵ�ϣ���map�Ĺؼ������Ʊ�����bean���Ե�����������һ��
	
	System.out.println(bean.getName());//aaa
	System.out.println(bean.getPassword());//123
	System.out.println(bean.getAge());//24�����Կ���ǰ̨���ݹ������ݶ������ַ������͵ģ�����bean����age������int�ͣ�Ҳ����beanUtils���֧�ֽ�ǰ̨���ַ��������Զ�ת��Ϊ���ֻ����������ݣ����Ǹ������ͣ��Ͳ������ˣ���Ҫ����Ϊ��������ע��һ��ת��������beanUtils�����ת����ȥ��ǰ̨string����ת��Ϊbean����ĸ����������ԣ�����������
	System.out.println(bean.getBirthday().toLocaleString());//1980-9-9 0:00:00
}
 
開發者ID:mushroomgithub,項目名稱:ServletStudyDemo,代碼行數:19,代碼來源:Demo1.java

示例15: Map2Bean

import org.apache.commons.beanutils.ConvertUtils; //導入依賴的package包/類
public static Object Map2Bean(Class type, Map map) throws Exception {
    ConvertUtils.register(new DateConvert(), Date.class);
    BeanInfo beanInfo = Introspector.getBeanInfo(type);
    Object obj = type.newInstance();
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor descriptor : propertyDescriptors) {
        String propertyName = descriptor.getName();
        if (!(map.containsKey(propertyName.toUpperCase())))
            continue;
        try {
            Object value = map.get(propertyName.toUpperCase());
            BeanUtils.setProperty(obj, propertyName, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return obj;
}
 
開發者ID:Hope6537,項目名稱:hope-tactical-equipment,代碼行數:19,代碼來源:BeanMapUtil.java


注:本文中的org.apache.commons.beanutils.ConvertUtils類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。