Example usage for org.apache.commons.lang3 ClassUtils primitiveToWrapper

List of usage examples for org.apache.commons.lang3 ClassUtils primitiveToWrapper

Introduction

In this page you can find the example usage for org.apache.commons.lang3 ClassUtils primitiveToWrapper.

Prototype

public static Class<?> primitiveToWrapper(final Class<?> cls) 

Source Link

Document

Converts the specified primitive Class object to its corresponding wrapper Class object.

NOTE: From v2.2, this method handles Void.TYPE , returning Void.TYPE .

Usage

From source file:ductive.console.commands.register.DefaultArgParserRegistry.java

@Override
public ArgParserRegistration find(Class<?> type_, String qualifier) {
    Class<?> type = ClassUtils.primitiveToWrapper(type_);
    return data.get(new RegistryKey(type, qualifier));
}

From source file:jp.furplag.util.commons.ObjectUtils.java

/**
 * substitute for {@link java.lang.Class#newInstance()}.
 *
 * @param type the Class object, return false if null.
 * @return empty instance of specified {@link java.lang.Class}.
 * @throws IllegalArgumentException// w  w w. j  a  v  a2  s . c  om
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws NegativeArraySizeException
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(final Class<T> type) throws InstantiationException {
    if (type == null)
        return null;
    if (type.isArray())
        return (T) Array.newInstance(type.getComponentType(), 0);
    if (Void.class.equals(ClassUtils.primitiveToWrapper(type))) {
        try {
            Constructor<Void> c = Void.class.getDeclaredConstructor();
            c.setAccessible(true);

            return (T) c.newInstance();
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        }

        return null;
    }

    if (type.isInterface()) {
        if (!Collection.class.isAssignableFrom(type))
            throw new InstantiationException(
                    "could not create instance, the type \"" + type.getName() + "\" is an interface.");
        if (List.class.isAssignableFrom(type))
            return (T) Lists.newArrayList();
        if (Map.class.isAssignableFrom(type))
            return (T) Maps.newHashMap();
        if (Set.class.isAssignableFrom(type))
            return (T) Sets.newHashSet();
    }

    if (type.isPrimitive()) {
        if (boolean.class.equals(type))
            return (T) Boolean.FALSE;
        if (char.class.equals(type))
            return (T) Character.valueOf(Character.MIN_VALUE);

        return (T) NumberUtils.valueOf("0", (Class<? extends Number>) type);
    }
    if (ClassUtils.isPrimitiveOrWrapper(type))
        return null;
    if (Modifier.isAbstract(type.getModifiers()))
        throw new InstantiationException(
                "could not create instance, the type \"" + type.getName() + "\" is an abstract class.");

    try {
        Constructor<?> c = type.getDeclaredConstructor();
        c.setAccessible(true);

        return (T) c.newInstance();
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }

    throw new InstantiationException("could not create instance, the default constructor of \"" + type.getName()
            + "()\" is not accessible ( or undefined ).");
}

From source file:de.openknowledge.jaxrs.versioning.conversion.FieldVersionProperty.java

private Object convert(Object value) {
    if (value == null || !isSimple() || type.isAssignableFrom(value.getClass())) {
        return value;
    }/*  www .jav  a 2  s  .c o  m*/
    Class<?> targetType = type.isPrimitive() ? ClassUtils.primitiveToWrapper(type) : type;
    try {
        return targetType.getConstructor(String.class).newInstance(value.toString());
    } catch (ReflectiveOperationException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.github.dozermapper.core.converters.PrimitiveOrWrapperConverter.java

private Converter getPrimitiveOrWrapperConverter(Class destClass, DateFormatContainer dateFormatContainer,
        String destFieldName, Object destObj) {
    if (String.class.equals(destClass)) {
        return new StringConverter(dateFormatContainer);
    }/*from   ww w  .  ja v  a2s.  c o m*/

    Converter result = CONVERTER_MAP.get(ClassUtils.primitiveToWrapper(destClass));

    if (result == null) {
        if (java.util.Date.class.isAssignableFrom(destClass)) {
            result = new DateConverter(dateFormatContainer.getDateFormat());
        } else if (Calendar.class.isAssignableFrom(destClass)) {
            result = new CalendarConverter(dateFormatContainer.getDateFormat());
        } else if (XMLGregorianCalendar.class.isAssignableFrom(destClass)) {
            result = new XMLGregorianCalendarConverter(dateFormatContainer.getDateFormat());
        } else if (MappingUtils.isEnumType(destClass)) {
            result = new EnumConverter();
        } else if (JAXBElement.class.isAssignableFrom(destClass) && destFieldName != null) {
            result = new JAXBElementConverter(destObj.getClass().getCanonicalName(), destFieldName,
                    dateFormatContainer.getDateFormat(), beanContainer);
        }
    }
    return result == null ? new StringConstructorConverter(dateFormatContainer) : result;
}

From source file:com.datatorrent.contrib.avro.PojoToAvro.java

/**
 * This method generates the getters for provided field of a given class
 *
 * @return Getter/*w  w  w  .  j  av a  2s. c o  m*/
 */
private Getter<?, ?> generateGettersForField(Class<?> cls, String inputFieldName)
        throws NoSuchFieldException, SecurityException {
    java.lang.reflect.Field f = cls.getDeclaredField(inputFieldName);
    Class<?> c = ClassUtils.primitiveToWrapper(f.getType());

    Getter<?, ?> classGetter = PojoUtils.createGetter(cls, inputFieldName, c);

    return classGetter;
}

From source file:com.adobe.acs.commons.util.impl.ValueMapTypeConverter.java

private Object handleArrayProperty(Class<?> clazz) {
    // handle case of primitive/wrapper arrays
    Class<?> componentType = clazz.getComponentType();
    if (componentType.isPrimitive()) {
        Class<?> wrapper = ClassUtils.primitiveToWrapper(componentType);
        if (wrapper != componentType) {
            Object wrapperArray = getValueFromMap(Array.newInstance(wrapper, 0).getClass());
            if (wrapperArray != null) {
                return unwrapArray(wrapperArray, componentType);
            }//from   w  w  w  .  j a v  a2  s .c  o m
        }
    } else {
        Object wrapperArray = getValueFromMap(Array.newInstance(componentType, 0).getClass());
        if (wrapperArray != null) {
            return unwrapArray(wrapperArray, componentType);
        }
    }
    return null;
}

From source file:com.datatorrent.lib.join.POJOJoinOperator.java

/**
 * Populate the getters from the input class
 *
 * @param isLeft isLeft specifies whether the class is left or right
 *///from   www.  ja  v  a2  s  .co  m
private void populateGettersFromInput(boolean isLeft) {
    Class inputClass;
    int idx;
    StoreContext store;
    if (isLeft) {
        idx = 0;
        inputClass = leftClass;
        store = leftStore;
    } else {
        idx = 1;
        inputClass = rightClass;
        store = rightStore;
    }
    String key = store.getKeys();
    String timeField = store.getTimeFields();
    String[] fields = store.getIncludeFields();

    // Create getter for the key field
    try {
        Class c = ClassUtils.primitiveToWrapper(inputClass.getField(key).getType());
        keyGetters[idx] = PojoUtils.createGetter(inputClass, key, c);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    }

    // Create getter for time field
    if (timeField != null) {
        try {
            Class c = ClassUtils.primitiveToWrapper(inputClass.getField(timeField).getType());
            timeGetters[idx] = PojoUtils.createGetter(inputClass, timeField, c);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    fieldMap[idx] = new LinkedList<FieldObjectMap>();
    List<FieldObjectMap> fieldsMap = fieldMap[idx];
    // Create getters for the include fields
    for (String f : fields) {
        try {
            Field field = inputClass.getField(f);
            Class c;
            if (field.getType().isPrimitive()) {
                c = ClassUtils.primitiveToWrapper(field.getType());
            } else {
                c = field.getType();
            }
            FieldObjectMap fm = new FieldObjectMap();
            fm.get = PojoUtils.createGetter(inputClass, f, c);
            fm.set = PojoUtils.createSetter(outputClass, f, c);
            fieldsMap.add(fm);
        } catch (Throwable e) {
            throw new RuntimeException("Failed to populate gettter for field: " + f, e);
        }
    }
}

From source file:io.github.moosbusch.lumpi.gui.form.spi.AbstractDynamicForm.java

protected final Form.Section createSection(Class<?> beanClass, PropertyDescriptor[] propDescs)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Form.Section result = new Form.Section();
    String sectHeading = getSectionHeading();
    Map<String, Class<?>> propertyMap = new HashMap<>();
    propertyMap.setComparator(Comparator.naturalOrder());

    if ((isShowSectionHeading()) && (StringUtils.isNotBlank(sectHeading))) {
        result.setHeading(sectHeading);/*from   w w w  .  j a  v  a  2 s.  c  o  m*/
    }

    for (PropertyDescriptor propDesc : propDescs) {
        propertyMap.put(propDesc.getName(), propDesc.getPropertyType());
    }

    for (String propertyName : propertyMap) {
        Class<?> propertyClass = ClassUtils.primitiveToWrapper(propertyMap.get(propertyName));

        FormEditor<? extends Component> editor;

        if (!isExcludedProperty(beanClass, propertyName)) {
            editor = getEditor(beanClass.getName(), propertyClass.getName(), propertyName);

            if (editor != null) {
                Component cmp = editor.getComponent();
                PropertyUtils.setProperty(cmp, editor.getDataBindingKeyPropertyName(), propertyName);
                setLabel(cmp, StringUtils.capitalize(propertyName));

                if (editor.isScrollable()) {
                    ScrollPane scroll = Objects.requireNonNull(createScrollPane());
                    scroll.setView(cmp);
                    result.add(scroll);
                } else {
                    result.add(cmp);
                }
            }
        }
    }

    return result;
}

From source file:com.crowsofwar.gorecore.config.ConfigLoader.java

/**
 * Tries to load the field of the {@link #obj object} with the correct
 * {@link #data}./*w w w .  j a  v a2 s . c o m*/
 * <p>
 * If the field isn't marked with @Load, does nothing. Otherwise, will
 * attempt to set the field's value (with reflection) to the data set in the
 * map.
 * 
 * @param field
 *            The field to load
 */
private <T> void loadField(Field field) {

    Class<?> cls = field.getDeclaringClass();
    Class<?> fieldType = field.getType();
    if (fieldType.isPrimitive())
        fieldType = ClassUtils.primitiveToWrapper(fieldType);

    try {

        if (field.getAnnotation(Load.class) != null) {

            if (Modifier.isStatic(field.getModifiers())) {

                GoreCore.LOGGER.log(Level.WARN,
                        "[ConfigLoader] Warning: Not recommended to mark static fields with @Load, may work out weirdly.");
                GoreCore.LOGGER.log(Level.WARN,
                        "This field is " + field.getDeclaringClass().getName() + "#" + field.getName());
                GoreCore.LOGGER.log(Level.WARN, "Use a singleton instead!");

            }

            // Should load this field

            HasCustomLoader loaderAnnot = fieldType.getAnnotation(HasCustomLoader.class);
            CustomLoaderSettings loaderInfo = loaderAnnot == null ? new CustomLoaderSettings()
                    : new CustomLoaderSettings(loaderAnnot);

            Object fromData = data.get(field.getName());
            Object setTo;

            boolean tryDefaultValue = fromData == null || ignoreConfigFile;

            if (tryDefaultValue) {

                // Nothing present- try to load default value

                if (field.get(obj) != null) {

                    setTo = field.get(obj);

                } else {
                    throw new ConfigurationException.UserMistake(
                            "No configured definition for " + field.getName() + ", no default value");
                }

            } else {

                // Value present in configuration.
                // Use the present value from map: fromData

                Class<Object> from = (Class<Object>) fromData.getClass();
                Class<?> to = fieldType;

                setTo = convert(fromData, to, field.getName());

            }
            usedValues.put(field.getName(), setTo);

            // If not a java class, probably custom; needs to NOT have the
            // '!!' in front
            if (!setTo.getClass().getName().startsWith("java")) {
                representer.addClassTag(setTo.getClass(), Tag.MAP);
                classTags.add(setTo.getClass());
            }

            // Try to apply custom loader, if necessary

            try {

                if (loaderInfo.hasCustomLoader())
                    loaderInfo.customLoaderClass.newInstance().load(null, setTo);

            } catch (InstantiationException | IllegalAccessException e) {

                throw new ConfigurationException.ReflectionException(
                        "Couldn't create a loader class of loader " + loaderInfo.customLoaderClass.getName(),
                        e);

            } catch (Exception e) {

                throw new ConfigurationException.Unexpected(
                        "An unexpected error occurred while using a custom object loader from config. Offending loader is: "
                                + loaderInfo.customLoaderClass,
                        e);

            }

            if (loaderInfo.loadFields)
                field.set(obj, setTo);

        }

    } catch (ConfigurationException e) {

        throw e;

    } catch (Exception e) {

        throw new ConfigurationException.Unexpected("An unexpected error occurred while loading field \""
                + field.getName() + "\" in class \"" + cls.getName() + "\"", e);

    }

}

From source file:com.jkoolcloud.tnt4j.streams.matchers.StringMatcher.java

private static Method findMatchingMethodAndConvertArgs(Object methodName, String[] arguments,
        Object[] convertedArguments, Method[] methods) {
    for (Method method : methods) {
        if (method.getName().equals(methodName) && method.getParameterTypes().length == arguments.length + 1) {
            boolean methodMatch = true;
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 1; i < parameterTypes.length; i++) {
                Class<?> parameterType = parameterTypes[i];
                if (CharSequence.class.isAssignableFrom(parameterType)) {
                    convertedArguments[i - 1] = arguments[i - 1];
                } else {
                    try {
                        if (parameterType.isPrimitive()) {
                            parameterType = ClassUtils.primitiveToWrapper(parameterType);
                        }//from  w w  w.j  a v a  2s  . c o m
                        Method converterMethod = parameterType.getMethod("valueOf", String.class);
                        convertedArguments[i - 1] = converterMethod.invoke(null, arguments[i - 1]);
                    } catch (Exception e) {
                        methodMatch = false;
                        break;
                    }
                }
            }

            if (methodMatch) {
                return method;
            }
        }
    }
    return null;
}