Java 类org.apache.commons.beanutils.Converter 实例源码

项目:NotifyTools    文件:ConverterFacade.java   
/**
 * Construct a converter which delegates to the specified
 * {@link Converter} implementation.
 *
 * @param converter The converter to delegate to
 */
public ConverterFacade(final Converter converter) {
    if (converter == null) {
        throw new IllegalArgumentException("Converter is missing");
    }
    this.converter = converter;
}
项目:spring-boot    文件:MyBeanUtils.java   
/**
 * 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);
}
项目:apex-core    文件:InjectConfigTest.java   
@Override
public void injectMembers(T t)
{
  try {
    LOG.debug("Processing " + annotation + " for field " + field);
    String value = conf.get(annotation.key());
    if (value == null) {
      if (annotation.optional() == false) {
        throw new IllegalArgumentException("Cannot inject " + annotation);
      }
      return;
    }
    Converter c = converters.lookup(field.getType());
    if (c == null) {
      throw new IllegalArgumentException("Cannot find a converter for: " + field);
    }
    field.set(t, c.convert(field.getType(), value));
  } catch (IllegalAccessException e) {
    throw new RuntimeException(e);
  }
}
项目:NotifyTools    文件:ArrayConverter.java   
/**
 * Construct an <b>array</b> <code>Converter</code> with the specified
 * <b>component</b> <code>Converter</code> that throws a
 * <code>ConversionException</code> if an error occurs.
 *
 * @param defaultType The default array type this
 *  <code>Converter</code> handles
 * @param elementConverter Converter used to convert
 *  individual array elements.
 */
public ArrayConverter(final Class<?> defaultType, final Converter elementConverter) {
    super();
    if (defaultType == null) {
        throw new IllegalArgumentException("Default type is missing");
    }
    if (!defaultType.isArray()) {
        throw new IllegalArgumentException("Default type must be an array.");
    }
    if (elementConverter == null) {
        throw new IllegalArgumentException("Component Converter is missing.");
    }
    this.defaultType = defaultType;
    this.elementConverter = elementConverter;
}
项目:infotranspub-backend    文件:EntityFieldMappingImpl.java   
public void translateFromCSVToObject(CsvEntityContext context,
    Map<String, Object> csvValues, BeanWrapper object) {

  if (isMissingAndOptional(csvValues))
    return;

  Converter converter = create(context);
  String entityId = (String) csvValues.get(_csvFieldName);
  Object entity = converter.convert(_objFieldType, entityId);
  object.setPropertyValue(_objFieldName, entity);
}
项目:apex-core    文件:StringCodecs.java   
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);
      }
    }
  }
}
项目:torgo    文件:UtilsBeanFactoryTest.java   
/**
 * Test of getConverter method, of class UtilsBeanFactory.
 */
@Test
public void testGetConverter() {
    System.out.println("getConverter");
    Class from = TypeHandler.class;
    Class to = Integer.class;
    Converter expResult = null;
    Converter result = UtilsBeanFactory.getConverter(from, to);
    assertNotNull(result);

    result = UtilsBeanFactory.getConverter(Date2.class, String.class);
    String res = result.convert(String.class, Calendar.getInstance().getTime());
    assertNotNull(result);

    result = UtilsBeanFactory.getConverter(Date2.class, UtilsBeanFactoryTest.class);
    assertNull(result);
}
项目:mtools    文件:FreemarkerUtils.java   
public String convert(Object value)
{
    if(value != null)
    {
        Class class1 = value.getClass();
        if(class1.isEnum() && super.lookup(class1) == null)
            super.register(new EnumConverter(class1), class1);
        else
        if(class1.isArray() && class1.getComponentType().isEnum())
        {
            if(super.lookup(class1) == null)
            {
                ArrayConverter arrayconverter = new ArrayConverter(class1, new EnumConverter(class1.getComponentType()), 0);
                arrayconverter.setOnlyFirstToString(false);
                super.register(arrayconverter, class1);
            }
            Converter converter = super.lookup(class1);
            return (String)converter.convert(String.class, value);
        }
    }
    return super.convert(value);
}
项目:replyit-master-3.2-final    文件:CsvExporter.java   
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;
}
项目:report    文件:BeanUtil.java   
/**
 * 数据转换
 * 
 * @param source
 *            源数据
 * 
 * @param targetType
 *            目标类型
 * 
 * @return
 */
public static Object convert(Object source, Class targetType) {
    Object result = source;
    if (null == targetType) {
        return result;
    }
    Converter converter = converterMap.get(targetType);
    if (null != converter) {
        result = converter.convert(targetType, source);
    }
    return result;
}
项目:my-paper    文件:SettingUtils.java   
@Override
public String convert(Object value) {
    if (value != null) {
        Class<?> type = value.getClass();
        if (type.isEnum() && super.lookup(type) == null) {
            super.register(new EnumConverter(type), type);
        } else if (type.isArray() && type.getComponentType().isEnum()) {
            if (super.lookup(type) == null) {
                ArrayConverter arrayConverter = new ArrayConverter(type, new EnumConverter(type.getComponentType()), 0);
                arrayConverter.setOnlyFirstToString(false);
                super.register(arrayConverter, type);
            }
            Converter converter = super.lookup(type);
            return ((String) converter.convert(String.class, value));
        }
    }
    return super.convert(value);
}
项目:my-paper    文件:FreemarkerUtils.java   
@Override
public String convert(Object value) {
    if (value != null) {
        Class<?> type = value.getClass();
        if (type.isEnum() && super.lookup(type) == null) {
            super.register(new EnumConverter(type), type);
        } else if (type.isArray() && type.getComponentType().isEnum()) {
            if (super.lookup(type) == null) {
                ArrayConverter arrayConverter = new ArrayConverter(type, new EnumConverter(type.getComponentType()), 0);
                arrayConverter.setOnlyFirstToString(false);
                super.register(arrayConverter, type);
            }
            Converter converter = super.lookup(type);
            return ((String) converter.convert(String.class, value));
        }
    }
    return super.convert(value);
}
项目:infotranspub-backend    文件:EntityFieldMappingImpl.java   
/****
 * {@link ConverterFactory}
 ****/

@Override
public Converter create(CsvEntityContext context) {
  GtfsReaderContext ctx = (GtfsReaderContext) context.get(GtfsReader.KEY_CONTEXT);
  return new ConverterImpl(ctx);
}
项目:excel-bean    文件:ExtConvertUtilsBean.java   
@Override
public Converter lookup(Class<?> clazz) {
    final Converter converter = super.lookup(clazz);
    if (converter == null && clazz.isEnum()) {
        return ENUM_CONVERTER;
    } else {
        return converter;
    }
}
项目:sosoapi-base    文件:CustConvertUtilsBean.java   
@Override
public Converter lookup(Class clazz) {
    //如果是枚举类型则设置为Enum.class
    if (clazz.isEnum()) {
        clazz = Enum.class;
    }

       return super.lookup(clazz);
   }
项目:jahhan    文件:BeanTools.java   
public static <S, D> D convertType(Object obj, Class<S> srcClass, Class<D> destClass) {
    if (srcClass.equals(destClass)) {
        return (D) JsonUtil.copyObject(obj);
    }
    Converter converter = convertUtils.lookup(srcClass, destClass);
    return converter.convert(destClass, obj);
}
项目:apex-core    文件:StringCodecs.java   
public static <T> void register(final Class<? extends StringCodec<?>> codec, final Class<T> clazz) throws InstantiationException, IllegalAccessException
{
  check();
  final StringCodec<?> codecInstance = codec.newInstance();
  ConvertUtils.register(new Converter()
  {
    @Override
    public Object convert(Class type, Object value)
    {
      return value == null ? null : codecInstance.fromString(value.toString());
    }

  }, clazz);
  codecs.put(clazz, codec);
}
项目:cereal    文件:ReflectionHelper.java   
/**
 * Convert the given object to be castable to the given <code>goal</code> type.
 * 
 * @param obj
 *            the object to convert
 * @param goal
 *            the goal type
 * 
 * @return the converted object
 */
public static Object convert(Object obj, Class<?> goal) {
    if (null == obj) {
        return obj;
    } else {
        if (goal.isInstance(obj)) {
            return obj;
        } else if (asPrimitive(goal).equals(asPrimitive(obj.getClass()))) {
            return obj;
        } else {
            Converter converter = ConvertUtils.lookup(goal);
            return (null != converter) ? converter.convert(goal, obj) : obj;
        }
    }
}
项目:torgo    文件:ClassConverterTest.java   
/**
 * Test of convert method, of class ClassConverter.
 */
@Test
public void testConvert() {
    LOGGER.info("class convert test");
    Converter lookup = UtilsBeanFactory.getConverter(String.class, Class.class);
    String hex = ClassConverter.class.getName();
    Class convert = lookup.convert(Class.class, hex);
    assertNotNull(convert);
    assertEquals(hex, convert.getName());
    Class fromString = (Class) TypeHandler.fromString(Class.class, hex);
    assertNotNull(fromString);
    assertEquals(hex, fromString.getName());
    fromString = (Class) TypeHandler.fromString(Class.class, "no.such.class");
    assertNull(fromString);
}
项目:invesdwin-util    文件:ValueObjectMerge.java   
private Object convertValue(final Object value, final Class<?> type) {
    if (value == null) {
        return null;
    }
    final Converter converter = getBeanUtilsBean().getConvertUtils().lookup(type);
    if (converter != null) {
        return converter.convert(type, value);
    } else {
        return value;
    }
}
项目:elide    文件:CoerceUtil.java   
/**
 * Perform CoerceUtil setup.
 */
private static void setup() {
    BeanUtilsBean.setInstance(new BeanUtilsBean(new ConvertUtilsBean() {
        {
            // https://github.com/yahoo/elide/issues/260
            // enable throwing exceptions when conversion fails
            register(true, false, 0);
        }

        @Override
        /*
         * Overriding lookup to execute enum converter if target is enum
         * or map convert if source is map
         */
        public Converter lookup(Class<?> sourceType, Class<?> targetType) {
            if (targetType.isEnum()) {
                return TO_ENUM_CONVERTER;
            } else if (targetType == UUID.class) {
                return TO_UUID_CONVERTER;
            }
            else if (Map.class.isAssignableFrom(sourceType)) {
                return FROM_MAP_CONVERTER;
            } else if ((String.class.isAssignableFrom(sourceType) || Number.class.isAssignableFrom(sourceType))
                    && ClassUtils.isAssignable(targetType, Date.class)) {
                return EPOCH_TO_DATE_CONVERTER;
            } else {
                return super.lookup(sourceType, targetType);
            }
        }
    }));
}
项目:torgo-android    文件:TypeHandler.java   
/**
 * Convert an object to a specified type.
 *
 * @param <T>
 * @param to
 * @param val
 * @return
 */
public static <T> T convert(Class<T> to, Object val) {
    Converter lookup = UtilsBeanFactory.getConverter(val.getClass(), to);
    if (lookup != null) {
        return lookup.convert(to, val);
    }

    return null;
}
项目:viewblock    文件:OtherRequestConvert.java   
@Override
public Object convert(Object tagValue, MethodParam methodParam) throws ViewBlockRequiredParameter {
    Converter converter = ConvertUtils.lookup(methodParam.getTypeClass());
    if (converter != null) {
        if (tagValue != null) {
            return convertUtilsBean1.convert(tagValue, methodParam.getTypeClass());
        } else if (methodParam.getDefValue() != null) {
            return methodParam.getDefValue();
        }
        return convertUtilsBean2.convert("", methodParam.getTypeClass());
    }
    return tagValue;
}
项目:restendpoint    文件:TextSerializer.java   
/**
 * Creates default TextSerializer and registers additional type converters
 *
 * @param typeConverters Map of type converters for serializer
 */
public TextSerializer(Map<Converter, Class<?>> typeConverters) {
    this();

    for (Map.Entry<Converter, Class<?>> typeConverter : typeConverters.entrySet()) {
        this.converter.register(typeConverter.getKey(), typeConverter.getValue());
    }
}
项目:sit-ad    文件:DocumentMapper.java   
@PostConstruct
public void initConverters() {
    if (log.isDebugEnabled()) {
        log.debug("Commons BeanUtilsのコンバータを登録します。{}", getConverterMap());
    }
    for (Entry<Class<?>, ? extends Converter> entry : getConverterMap().entrySet()) {
        ConvertUtils.register(entry.getValue(), entry.getKey());
    }

}
项目:mayaa    文件:ObjectUtil.java   
/**
 * オブジェクトを指定したクラスのインスタンスに変換して返します。
 * 変換の必要が無い場合はそのまま返します。
 *
 * @param expectedClass 戻り型として期待するクラス
 * @param value 変換する値
 * @return 変換後の値 (expectedClassのインスタンス)
 */
public static Object convert(Class expectedClass, Object value) {
    if (Object.class.equals(expectedClass) ||
            (value != null && expectedClass.isAssignableFrom(value.getClass()))) {
        return value;
    }
    if (String.class.equals(expectedClass)) {
        return (value != null) ? value.toString() : null;
    }
    if (Boolean.class.equals(expectedClass) || Boolean.TYPE.equals(expectedClass)) {
        if (value instanceof Boolean) {
            return value;
        }
        return Boolean.valueOf(ObjectUtil.booleanValue(value, false));
    }
    Converter converter = ConvertUtils.lookup(expectedClass);
    if (converter != null) {
        if (value != null) {
            return converter.convert(expectedClass, value);
        }
        if (expectedClass.isPrimitive() || Number.class.isAssignableFrom(expectedClass)) {
            if (BigInteger.class.isAssignableFrom(expectedClass)) {
                return BigInteger.ZERO;
            } else if (BigDecimal.class.isAssignableFrom(expectedClass)) {
                return BigDecimal.valueOf(0);
            }
            return converter.convert(expectedClass, value);
        }
    }
    return value;
}
项目:checkstyle-backport-jre6    文件:AutomaticBeanTest.java   
@Override
public void register(Converter converter, Class<?> clazz) {
    super.register(converter, clazz);
    registerCount++;
}
项目:ServletStudyDemo    文件:Demo1.java   
@Test
public void test3() throws Exception{
    String name="aaa";
    String password="123";
    String age="24";
    String birthday="1980-09-09";

    //Ϊ�������ڸ���bean��birthday�����ϣ����Ǹ�beanUtilsע��һ������ת������beanUtilsΪ��ָ����Ϊ��������ע��ת�����ķ���ConvertUtils������
    ConvertUtils.register(new Converter(){//��beanUtilsת��֮ǰע������ת���������͵�ת����

        public Object convert(Class type, Object value) {//���������beanUtils���ã���value�ַ���������ֵת��Ϊ���ӵ�type����(������Date����)
            //���ȼ��ǰ̨���������ַ�������value�Ƿ�Ϊ�գ�Ϊ�ղ�����ת��
            if(value==null){
                return null;
            }

            if(!(value instanceof String)){//�ж�beanUtils���ݽ�����ǰ̨Ҫת��Ϊ�������͵������Dz���String����
                throw new RuntimeException("֧��String���͵�ת��");
            }

            String str=(String)value;//��valueת��ΪString����
            if(str.trim().equals("")){//��ֹǰ̨���ݹ������ַ�����һϵ�еĿո���  ��     ��
                return null;
            }
            //˵�����ַ�������ֵ
            SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
            try {
                return df.parse(str);
            } catch (ParseException e) {
                throw new RuntimeException(e);//���ܲ�д���e���쳣�����ܶ�
            }
        }
    }, Date.class);//ΪbeanUtilsע��һ��ʵ�ֽ��ַ���ת��Ϊclazz��ʾ�ĸ������͵�ת����

    Person bean=new Person();
    BeanUtils.setProperty(bean, "name", name);//��ʾ�����ĸ�bean���ĸ����ԣ���Ϊ������Ը�ֵΪvalue
    BeanUtils.setProperty(bean, "password", password);//ֻ֧���ַ�����8�ֻ������������Զ�ת��
    BeanUtils.setProperty(bean, "age", age);
    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
}
项目:activemq-artemis    文件:BeanSupport.java   
public static void registerConverter(Converter converter, Class type) {
   synchronized (beanUtils) {
      beanUtils.getConvertUtils().register(converter, type);
   }
}
项目:GeneralUtils    文件:ExcelBuilder.java   
public Converter[] getConverters() {
    return converters;
}
项目:GeneralUtils    文件:ExcelBuilder.java   
public void setConverters(Converter[] converters) {
    this.converters = converters;
}
项目:sit-ad    文件:DocumentMapper.java   
public Map<Class<?>, ? extends Converter> getConverterMap() {
    return converterMap;
}
项目:sit-ad    文件:DocumentMapper.java   
public void setConverterMap(Map<Class<?>, ? extends Converter> converterMap) {
    this.converterMap = converterMap;
}
项目:checkstyle    文件:AutomaticBeanTest.java   
@Override
public void register(Converter converter, Class<?> clazz) {
    super.register(converter, clazz);
    registerCount++;
}
项目:msInspect    文件:AbstractConvertHelper.java   
protected void _register(Converter conv, Class cl)
{
    ConvertUtils.register(conv, cl);
}
项目:msInspect    文件:AbstractConvertHelper.java   
public NullSafeConverter(Converter converter)
{
    _converter = converter;
}
项目:msInspect    文件:ConvertHelper.java   
PercentWrapper(Converter converter)
{
    this.conv = converter;
}
项目:msInspect    文件:ConvertHelper.java   
ChargeWrapper(Converter converter)
{
    this.conv = converter;
}
项目:NotifyTools    文件:ArrayConverter.java   
/**
 * Construct an <b>array</b> <code>Converter</code> with the specified
 * <b>component</b> <code>Converter</code> that returns a default
 * array of the specified size (or <code>null</code>) if an error occurs.
 *
 * @param defaultType The default array type this
 *  <code>Converter</code> handles
 * @param elementConverter Converter used to convert
 *  individual array elements.
 * @param defaultSize Specifies the size of the default array value or if less
 *  than zero indicates that a <code>null</code> default value should be used.
 */
public ArrayConverter(final Class<?> defaultType, final Converter elementConverter, final int defaultSize) {
    this(defaultType, elementConverter);
    this.defaultSize = defaultSize;
    Object defaultValue = null;
    if (defaultSize >= 0) {
        defaultValue = Array.newInstance(defaultType.getComponentType(), defaultSize);
    }
    setDefaultValue(defaultValue);
}
项目:my-paper    文件:ExcelView.java   
/**
 * @param filename
 *            文件名称
 * @param sheetName
 *            表名称
 * @param properties
 *            属性
 * @param titles
 *            标题
 * @param widths
 *            列宽
 * @param converters
 *            类型转换
 * @param data
 *            数据
 * @param contents
 *            附加内容
 */
public ExcelView(String filename, String sheetName, String[] properties, String[] titles, Integer[] widths, Converter[] converters, Collection<?> data, String[] contents) {
    this.filename = filename;
    this.sheetName = sheetName;
    this.properties = properties;
    this.titles = titles;
    this.widths = widths;
    this.converters = converters;
    this.data = data;
    this.contents = contents;
}