Java Code Examples for org.apache.commons.lang3.ClassUtils#isPrimitiveOrWrapper()

The following examples show how to use org.apache.commons.lang3.ClassUtils#isPrimitiveOrWrapper() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResponseRootDeserializer.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public static boolean needConvert(Object obj, JavaType invocationTimeType) {
  if (obj == null || ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || invocationTimeType.isPrimitive()
      || ProtoConst.OBJECT_TYPE.equals(invocationTimeType)) {
    return false;
  }

  if (obj.getClass() == invocationTimeType.getRawClass()) {
    return false;
  }

  if (invocationTimeType.getRawClass().isAssignableFrom(obj.getClass())) {
    if (invocationTimeType.getContentType() == null) {
      return false;
    }
  }

  return true;
}
 
Example 2
Source File: SwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public static boolean isBean(Type type) {
  if (type == null) {
    return false;
  }

  JavaType javaType = TypeFactory.defaultInstance().constructType(type);
  if (javaType.isContainerType() || javaType.isEnumType()) {
    return false;
  }

  Class<?> cls = javaType.getRawClass();
  if (ClassUtils.isPrimitiveOrWrapper(cls)) {
    return false;
  }

  return (cls != String.class
      && cls != Date.class
      && cls != LocalDate.class
      && cls != byte[].class
      && cls != File.class
      && !cls.getName().equals("org.springframework.web.multipart.MultipartFile")
      && !Part.class.isAssignableFrom(cls));
}
 
Example 3
Source File: BusinessObjectBase.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Override
public String toString() {
       class BusinessObjectToStringBuilder extends ReflectionToStringBuilder {

           private BusinessObjectToStringBuilder(Object object) {
               super(object);
           }

           @Override
           public boolean accept(Field field) {
               return String.class.isAssignableFrom(field.getType())
                       || ClassUtils.isPrimitiveOrWrapper(field.getType());
           }

       }

       return new BusinessObjectToStringBuilder(this).toString();
   }
 
Example 4
Source File: TypeConverter.java    From DataDefender with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the passed value to the passed type if possible.
 *
 * Conversion is performed in the following order:
 *  - Returned as-is if the value is of the same type or a sub-class of the
 *    type.
 *  - If type is java.lang.String, call toString on value and return it.
 *  - If value is a primitive, primitive wrapper, or String, and type
 *    represents one of those as well, an attempt is made to convert from/to
 *    as needed.
 *  - Otherwise, look for a constructor in the passed type that accepts a
 *    single argument of:
 *    o value itself (as its type or an interface/superclass)
 *    o A String argument, in which case toString is called on value
 *    o If value is primitive, the primitive type or it's wrapper
 *    o If value is a String, a primitive or wrapper argument
 *
 * @param value
 * @param type
 * @return
 */
public static Object convert(Object value, Class<?> type)
    throws InstantiationException,
    IllegalAccessException,
    IllegalArgumentException,
    InvocationTargetException {
    if (ClassUtils.isAssignable(value.getClass(), type)) {
        return value;
    } else if (String.class.equals(type)) {
        return value.toString();
    } else if (ClassUtils.isPrimitiveOrWrapper(type) && value instanceof String) {
        return ConvertUtils.convert(value, type);
    }
    Constructor<?> constr = getConvertibleConstructor(value.getClass(), type);
    Class<?> pt = (constr != null && constr.getParameterCount() > 0) ? constr.getParameterTypes()[0] : null;
    if (!ClassUtils.isAssignable(value.getClass(), pt)) {
        if (pt != null && ClassUtils.isAssignable(String.class, pt)) {
            return constr.newInstance(value.toString());
        } else if (pt != null && ClassUtils.isPrimitiveOrWrapper(pt) && value instanceof String) {
            return constr.newInstance(ConvertUtils.convert(value, pt));
        }
        // try anyway...
    }

    return constr.newInstance(value);
}
 
Example 5
Source File: TypeConverter.java    From DataDefender with Apache License 2.0 6 votes vote down vote up
private static int getConversionScore(Class<?> from, Class<?> to) {
    if (from.equals(to)) {
        return Integer.MAX_VALUE;
    } else if (ClassUtils.isAssignable(from, to)) {
        return Integer.MAX_VALUE - 1;
    } else if (String.class.equals(to)) {
        return Integer.MAX_VALUE - 2;
    } else if (ClassUtils.isPrimitiveOrWrapper(to) && String.class.isAssignableFrom(from)) {
        return Integer.MAX_VALUE - 3 - primitiveOrder.indexOf(to);
    }
    List<Class<?>> ordered = buildOrderedListForType(to);
    if (ordered.contains(from)) {
        return Integer.MAX_VALUE - 100 - ordered.indexOf(from);
    }
    int ind = 0;
    for (Class<?> conv : ordered) {
        ++ind;
        if (isConvertible(conv, to)) {
            return Integer.MAX_VALUE - 200 - ind;
        }
    }
    return Integer.MIN_VALUE;
}
 
Example 6
Source File: GsonInterfaceAdapter.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@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;
  }
  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;
}
 
Example 7
Source File: PropertyUtil.java    From minnal with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the given type represents a "simple" value type:
 * a primitive, a String or other CharSequence, a Number, a Date,
 * a URI, a URL, a Locale or a Class.
 * 
 * @param clazz the type to check
 * @return whether the given type represents a "simple" value type
 */
public static boolean isSimpleValueType(Class<?> clazz) {
	return ClassUtils.isPrimitiveOrWrapper(clazz) || clazz.isEnum() ||
			CharSequence.class.isAssignableFrom(clazz) ||
			Number.class.isAssignableFrom(clazz) ||
			Date.class.isAssignableFrom(clazz) ||
			clazz.equals(URI.class) || clazz.equals(URL.class) ||
			clazz.equals(Locale.class) || clazz.equals(Class.class) || 
			clazz.equals(Serializable.class) || clazz.equals(Timestamp.class);
}
 
Example 8
Source File: MemcachedClientBuilder.java    From ob1k with Apache License 2.0 5 votes vote down vote up
/**
 * Create a client builder for MessagePack values.
 * @return The builder
 */
public static <T> MemcachedClientBuilder<T> newMessagePackClient(final MessagePack messagePack, final Class<T> valueType) {
  if (!ClassUtils.isPrimitiveOrWrapper(valueType)) {
    messagePack.register(valueType);
  }
  return newClient(new MessagePackTranscoder<>(messagePack, valueType));
}
 
Example 9
Source File: TypeConverter.java    From DataDefender with Apache License 2.0 5 votes vote down vote up
private static List<Class<?>> buildOrderedListForType(Class<?> from) {
    List<Class<?>> list = new ArrayList<>();
    list.add(from);
    if (ClassUtils.isPrimitiveOrWrapper(from)) {
        list.add(from.isPrimitive() ? ClassUtils.primitiveToWrapper(from) : ClassUtils.wrapperToPrimitive(from));
    }
    if (String.class.equals(from)) {
        list.addAll(primitiveOrder);
    } else {
        list.add(String.class);
    }
    return list;
}
 
Example 10
Source File: TypeConverter.java    From DataDefender with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if an object of type "from" can be converted to type "to" by
 * the 'convert' method.
 *
 * @param from
 * @param to
 * @return
 */
public static boolean isConvertible(Class<?> from, Class<?> to) {
    if (ClassUtils.isAssignable(from, to) || String.class.equals(to)) {
        return true;
    } else if (ClassUtils.isPrimitiveOrWrapper(from) && String.class.isAssignableFrom(from)) {
        return true;
    }
    return (getConvertibleConstructor(from, to) != null);
}
 
Example 11
Source File: AbstractServiceClient.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
protected String encodeUrl(Object url) throws JsonProcessingException {
    if (url == null) {
        return "";
    }

    if (url instanceof String) {
        return encodeUrl((String) url);
    } else if (ClassUtils.isPrimitiveOrWrapper(url.getClass()) || url.getClass().isEnum()) {
        return String.valueOf(url);
    } else {
        return encodeUrl(objectMapper.writeValueAsString(url));
    }
}
 
Example 12
Source File: ReflectionUtils.java    From confucius-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Read fields value as {@link Map}
 *
 * @param object
 *         object to be read
 * @return fields value as {@link Map}
 */
@Nonnull
public static Map<String, Object> readFieldsAsMap(Object object) {
    Map<String, Object> fieldsAsMap = Maps.newLinkedHashMap();
    Class<?> type = object.getClass();
    Field[] fields = type.getDeclaredFields();
    for (Field field : fields) {

        if (Modifier.isStatic(field.getModifiers())) { // To filter static fields
            continue;
        }

        field.setAccessible(true);

        try {
            String fieldName = field.getName();
            Object fieldValue = field.get(object);
            if (fieldValue != null) {
                Class<?> fieldValueType = fieldValue.getClass();
                if (ClassUtils.isPrimitiveOrWrapper(fieldValueType)) {
                } else if (fieldValueType.isArray()) {
                    fieldValue = toList(fieldValue);
                } else if ("java.lang".equals(fieldValueType.getPackage().getName())) {

                } else {
                    fieldValue = readFieldsAsMap(fieldValue);
                }
            }
            fieldsAsMap.put(fieldName, fieldValue);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return fieldsAsMap;
}
 
Example 13
Source File: IndexResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static boolean isTerminalType(Class<?> type) {
	return ClassUtils.isPrimitiveOrWrapper(type)
			|| type.isEnum()
			|| Date.class.isAssignableFrom(type)
			|| String.class.equals(type)
			|| Object.class.equals(type);
}
 
Example 14
Source File: LocOkHttpClient.java    From loc-framework with MIT License 5 votes vote down vote up
private boolean isPrimitiveType(Type type) {
  if (type instanceof Class) {
    Class clazz = (Class) type;
    if (ClassUtils.isPrimitiveOrWrapper(clazz) || ClassUtils
        .isAssignable(clazz, String.class)) {
      return true;
    }
  }
  return false;
}
 
Example 15
Source File: ConnConfPropertyListView.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void populateItem(final ListItem<ConnConfProperty> item) {
    final ConnConfProperty property = item.getModelObject();

    final String label = StringUtils.isBlank(property.getSchema().getDisplayName())
            ? property.getSchema().getName() : property.getSchema().getDisplayName();

    final FieldPanel<? extends Serializable> field;
    boolean required = false;
    boolean isArray = false;

    if (property.getSchema().isConfidential()
            || IdMConstants.GUARDED_STRING.equalsIgnoreCase(property.getSchema().getType())
            || IdMConstants.GUARDED_BYTE_ARRAY.equalsIgnoreCase(property.getSchema().getType())) {

        field = new AjaxPasswordFieldPanel("panel", label, new Model<>(), false);
        ((PasswordTextField) field.getField()).setResetPassword(false);

        required = property.getSchema().isRequired();
    } else {
        Class<?> propertySchemaClass;
        try {
            propertySchemaClass = ClassUtils.getClass(property.getSchema().getType());
            if (ClassUtils.isPrimitiveOrWrapper(propertySchemaClass)) {
                propertySchemaClass = ClassUtils.primitiveToWrapper(propertySchemaClass);
            }
        } catch (ClassNotFoundException e) {
            LOG.error("Error parsing attribute type", e);
            propertySchemaClass = String.class;
        }

        if (ClassUtils.isAssignable(Number.class, propertySchemaClass)) {
            @SuppressWarnings("unchecked")
            Class<Number> numberClass = (Class<Number>) propertySchemaClass;
            field = new AjaxSpinnerFieldPanel.Builder<>().build("panel", label, numberClass, new Model<>());
            required = property.getSchema().isRequired();
        } else if (ClassUtils.isAssignable(Boolean.class, propertySchemaClass)) {
            field = new AjaxCheckBoxPanel("panel", label, new Model<>());
        } else {
            field = new AjaxTextFieldPanel("panel", label, new Model<>());
            required = property.getSchema().isRequired();
        }

        if (propertySchemaClass.isArray()) {
            isArray = true;
        }
    }

    field.setIndex(item.getIndex());
    field.setTitle(property.getSchema().getHelpMessage(), true);

    final AbstractFieldPanel<? extends Serializable> fieldPanel;
    if (isArray) {
        final MultiFieldPanel multiFieldPanel = new MultiFieldPanel.Builder(
                new PropertyModel<>(property, "values")).setEventTemplate(true).build("panel", label, field);
        item.add(multiFieldPanel);
        fieldPanel = multiFieldPanel;
    } else {
        setNewFieldModel(field, property.getValues());
        item.add(field);
        fieldPanel = field;
    }

    if (required) {
        fieldPanel.addRequiredLabel();
    }

    if (withOverridable) {
        fieldPanel.showExternAction(addCheckboxToggle(property));
    }
}
 
Example 16
Source File: ReflectionUtil.java    From glitr with MIT License 4 votes vote down vote up
private static boolean isSupportedType(Class<?> clazz) {
    return !(ClassUtils.isPrimitiveOrWrapper(clazz) || clazz == Object.class || Map.class.isAssignableFrom(clazz));
}
 
Example 17
Source File: ActivitiResourceMapper.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private boolean isPrimitive(Class clazz) {
	return clazz == String.class || ClassUtils.isPrimitiveOrWrapper(clazz) || LocalDate.class.getPackage().equals(clazz
			.getPackage()) || clazz.isEnum() || clazz == UUID.class;
}
 
Example 18
Source File: PropertyUtil.java    From feilong-core with Apache License 2.0 3 votes vote down vote up
/**
 * 一般自定义的command 里面 就是些 string int,list map等对象.
 * 
 * <p>
 * 这些我们过滤掉,只取类型是 findedClassType的
 * </p>
 * 
 * @param obj
 *            the obj
 * @return true, if checks if is can find type
 * @since 1.6.3
 */
private static boolean isDonotSupportFindType(Object obj){
    //一般自定义的command 里面 就是些 string int,list map等对象
    //这些我们过滤掉,只取类型是 findedClassType的
    return ClassUtils.isPrimitiveOrWrapper(obj.getClass())//
                    || ClassUtil.isInstanceAnyClass(obj, CharSequence.class, Collection.class, Map.class);
}
 
Example 19
Source File: KafkaEmitter.java    From metron with Apache License 2.0 2 votes vote down vote up
/**
 * The result of a profile's triage expressions must be a string or primitive type.
 *
 * This ensures that the value can be easily serialized and appended to a message destined for Kafka.
 *
 * @param value The value of a triage expression.
 * @return True, if the type of the value is valid.
 */
private boolean isValidType(Object value) {
  return value != null && (value instanceof String || ClassUtils.isPrimitiveOrWrapper(value.getClass()));
}