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

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

Introduction

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

Prototype

public static boolean isPrimitiveOrWrapper(final Class<?> type) 

Source Link

Document

Returns whether the given type is a primitive or primitive wrapper ( Boolean , Byte , Character , Short , Integer , Long , Double , Float ).

Usage

From source file:gobblin.util.io.GsonInterfaceAdapter.java

@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (ClassUtils.isPrimitiveOrWrapper(type.getRawType()) || type.getType() instanceof GenericArrayType
            || CharSequence.class.isAssignableFrom(type.getRawType())
            || (type.getType() instanceof ParameterizedType
                    && (Collection.class.isAssignableFrom(type.getRawType())
                            || Map.class.isAssignableFrom(type.getRawType())))) {
        // delegate primitives, arrays, collections, and maps
        return null;
    }//from  w  w w. j a v  a  2  s . com
    if (!this.baseClass.isAssignableFrom(type.getRawType())) {
        // delegate anything not assignable from base class
        return null;
    }
    TypeAdapter<R> adapter = new InterfaceAdapter<>(gson, this, type);
    return adapter;
}

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

private boolean isSimple(Class<?> type) {
    return type == String.class || type == Date.class || ClassUtils.isPrimitiveOrWrapper(type);
}

From source file:it.andreascarpino.ansible.inventory.type.AnsibleVariable.java

public String objToString(Object value) {
    final StringBuilder buf = new StringBuilder();

    for (Field f : value.getClass().getDeclaredFields()) {
        f.setAccessible(true);//  ww w  . jav  a2  s .  co  m

        try {
            buf.append("'" + f.getName() + "': ");
            if (ClassUtils.isPrimitiveOrWrapper(value.getClass()) || value instanceof String) {
                buf.append("'" + value + "'");
            } else {
                buf.append(valueToString(f.get(value)));
            }
            buf.append(", ");
        } catch (IllegalArgumentException | IllegalAccessException e) {
            // Silently ignore errors
            e.printStackTrace();
        }
    }
    buf.replace(buf.length() - 2, buf.length(), "");

    return buf.toString();
}

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 ww  .  ja v a  2  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:it.andreascarpino.ansible.inventory.type.AnsibleVariable.java

public String listToString(Collection<?> list) {
    final StringBuilder buf = new StringBuilder();
    buf.append("'[");

    if (!list.isEmpty()) {
        for (Object o : list) {
            if (ClassUtils.isPrimitiveOrWrapper(o.getClass()) || o instanceof String) {
                buf.append("'" + o + "'");
            } else {
                buf.append(valueToString(o));
            }//from   ww w .  ja va 2s.  c  o m
            buf.append(", ");
        }
        buf.replace(buf.length() - 2, buf.length(), "");
    }

    buf.append("]'");

    return buf.toString();
}

From source file:de.bund.bva.pliscommon.serviceapi.core.serviceimpl.MappingHelper.java

/**
 * Bildet ein Objekt mithilfe von Dozer auf einen gewnschten Zieltyp ab. Im Gegensatz zu
 * {@link Mapper#map(Object, Class)} knnen als Zieltyp auch generische Collections, String und primitive
 * Typen bergeben werden./* ww w.j a  va  2s . c o  m*/
 * 
 * @param mapper
 *            der Dozer-Mapper
 * @param source
 *            das zu mappende Objekt
 * @param destinationType
 *            der Zieltyp
 * @return das gemappte Objekt
 */
@SuppressWarnings("unchecked")
public static Object map(Mapper mapper, Object source, Type destinationType) {
    if (source == null) {
        return null;
    }

    if (destinationType instanceof ParameterizedType) {
        ParameterizedType parDestinationType = (ParameterizedType) destinationType;

        Class<?> rawClass = (Class<?>) parDestinationType.getRawType();
        if (List.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new ArrayList<Object>());
        } else if (SortedSet.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new TreeSet<Object>());
        } else if (Set.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new HashSet<Object>());
        } else if (SortedMap.class.isAssignableFrom(rawClass)) {
            return mapMap(mapper, source, parDestinationType, new TreeMap<Object, Object>());
        } else if (Map.class.isAssignableFrom(rawClass)) {
            return mapMap(mapper, source, parDestinationType, new HashMap<Object, Object>());
        }

        destinationType = parDestinationType.getRawType();
    }

    if (destinationType instanceof GenericArrayType) {
        if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType
                    + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: "
                    + source.getClass());
        }

        // wir werden im Array Element pro Element mappen
        Type elementType = ((GenericArrayType) destinationType).getGenericComponentType();
        Object[] sourceArray = (Object[]) source;
        Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length);
        for (int i = 0; i < sourceArray.length; i++) {
            destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType);
        }
        return destinationArray;
    } else if ((destinationType instanceof Class<?>) && ((Class<?>) destinationType).isArray()) {
        if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType
                    + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: "
                    + source.getClass());
        }
        Class<?> destinationTypeClass = (Class<?>) destinationType;
        // wir werden im Array Element pro Element mappen
        Type elementType = destinationTypeClass.getComponentType();
        Object[] sourceArray = (Object[]) source;
        Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length);
        for (int i = 0; i < sourceArray.length; i++) {
            destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType);
        }
        return destinationArray;
    }

    if (!(destinationType instanceof Class<?>)) {
        throw new IllegalArgumentException(
                "Ein Mapping auf Typ " + destinationType + " wird nicht untersttzt");
    }

    Class<?> destinationClass = (Class<?>) destinationType;

    if (ClassUtils.isPrimitiveOrWrapper(destinationClass) || MAPPING_BLACKLIST.contains(destinationClass)) {
        return source;
    } else if (destinationClass.isEnum()) {
        // wir mssen auf dieser Ebene Enums leider manuell mappen
        if (!(source instanceof Enum)) {
            throw new IllegalArgumentException("Ein Mapping auf ein Enum " + destinationClass
                    + " wird nicht untersttzt, da das Quellobjekt kein Enumobjekt ist (Quellobjektstyp: "
                    + source.getClass().toString() + ").");
        }
        return Enum.valueOf((Class<Enum>) destinationClass, ((Enum<?>) source).name());
    } else {
        return mapper.map(source, destinationClass);
    }
}

From source file:it.andreascarpino.ansible.inventory.type.AnsibleVariable.java

public String mapToString(Map<?, ?> map) {
    final StringBuilder buf = new StringBuilder();
    buf.append("{");

    if (!map.isEmpty()) {
        for (Entry<?, ?> o : map.entrySet()) {
            final Object v = o.getValue();

            if (v != null) {
                buf.append("'" + o.getKey() + "': ");
                if (ClassUtils.isPrimitiveOrWrapper(v.getClass()) || v instanceof String) {
                    buf.append("'" + v + "'");
                } else {
                    buf.append(valueToString(v));
                }/*from  w  w  w  .  jav  a2 s .c  om*/
                buf.append(", ");
            }
        }
        buf.replace(buf.length() - 2, buf.length(), "");
    }

    buf.append("}");

    return buf.toString();
}

From source file:com.github.jknack.handlebars.internal.js.RhinoHandlebars.java

/**
 * True if the object is natively supported by Rhino.
 *
 * @param object An object.//from w  ww.  j  a  v a 2 s  . co m
 * @return True if the object is natively supported by Rhino.
 */
private static boolean isSupportedType(final Object object) {
    if (object == null) {
        return true;
    }
    if (CharSequence.class.isInstance(object)) {
        return true;
    }
    return ClassUtils.isPrimitiveOrWrapper(object.getClass());
}

From source file:com.artistech.protobuf.TuioProtoConverter.java

@Override
public GeneratedMessage.Builder convertToProtobuf(Object obj) {
    GeneratedMessage.Builder builder;// ww w . j  ava 2 s.  c om

    if (obj.getClass().getName().equals(TUIO.TuioTime.class.getName())) {
        builder = TuioProtos.Time.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioCursor.class.getName())) {
        builder = TuioProtos.Cursor.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioObject.class.getName())) {
        builder = TuioProtos.Object.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioBlob.class.getName())) {
        builder = TuioProtos.Blob.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioPoint.class.getName())) {
        builder = TuioProtos.Point.newBuilder();
    } else {
        return null;
    }

    try {
        PropertyDescriptor[] objProps = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors();
        BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass());
        PropertyDescriptor[] builderProps = beanInfo.getPropertyDescriptors();
        Method[] methods = builder.getClass().getMethods();
        for (PropertyDescriptor prop1 : objProps) {
            for (PropertyDescriptor prop2 : builderProps) {
                if (prop1.getName().equals(prop2.getName())) {
                    Method readMethod = prop1.getReadMethod();
                    ArrayList<Method> methodsToTry = new ArrayList<>();
                    for (Method m : methods) {
                        if (m.getName().equals(readMethod.getName().replaceFirst("get", "set"))) {
                            methodsToTry.add(m);
                        }
                    }

                    for (Method setMethod : methodsToTry) {
                        try {
                            if (Iterable.class.isAssignableFrom(readMethod.getReturnType())) {
                                if (DeepCopy) {
                                    ArrayList<Method> methodsToTry2 = new ArrayList<>();
                                    for (Method m : methods) {
                                        if (m.getName()
                                                .equals(readMethod.getName().replaceFirst("get", "add"))) {
                                            methodsToTry2.add(m);
                                        }
                                    }

                                    boolean success = false;
                                    for (Method setMethod2 : methodsToTry2) {
                                        Iterable iter = (Iterable) readMethod.invoke(obj);
                                        Iterator it = iter.iterator();
                                        while (it.hasNext()) {
                                            Object o = it.next();
                                            //call set..
                                            for (ProtoConverter converter : services) {
                                                if (converter.supportsConversion(o)) {
                                                    try {
                                                        GeneratedMessage.Builder convertToProtobuf = converter
                                                                .convertToProtobuf(o);
                                                        setMethod2.invoke(builder, convertToProtobuf);
                                                        success = true;
                                                        break;
                                                    } catch (IllegalAccessException | IllegalArgumentException
                                                            | InvocationTargetException ex) {

                                                    }
                                                }
                                            }
                                        }
                                        if (success) {
                                            break;
                                        }
                                    }
                                }
                            } else {
                                boolean primitiveOrWrapper = ClassUtils
                                        .isPrimitiveOrWrapper(readMethod.getReturnType());

                                if (primitiveOrWrapper) {
                                    setMethod.invoke(builder, readMethod.invoke(obj));
                                } else {
                                    Object invoke = readMethod.invoke(obj);
                                    com.google.protobuf.GeneratedMessage.Builder val = convertToProtobuf(
                                            invoke);

                                    setMethod.invoke(builder, val);
                                    break;
                                }
                            }
                        } catch (IllegalAccessException | IllegalArgumentException
                                | InvocationTargetException ex) {
                            //                            Logger.getLogger(TuioProtoConverter.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                }
            }
        }
    } catch (IntrospectionException ex) {
        logger.fatal(ex);
    }

    return builder;
}

From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java

public static boolean isPrimitiveTypeOrString(Class<?> type) {
    return (ClassUtils.isPrimitiveOrWrapper(type) || (ClassUtils.isAssignable(type, String.class)));
}