List of usage examples for java.lang Class isEnum
public boolean isEnum()
From source file:org.gvnix.web.datatables.util.QuerydslUtils.java
/** * Utility for constructing where clause expressions. * /*w w w . j ava2s . c om*/ * @param entityPath Full path to entity and associations. For example: * {@code Pet} , {@code Pet.owner} * @param fieldName Property name in the given entity path. For example: * {@code name} in {@code Pet} entity, {@code firstName} in * {@code Pet.owner} entity. * @param fieldType Property value {@code Class} * @param searchStr the value to find, may be null * @return Predicate */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Predicate createExpression(PathBuilder<T> entityPath, String fieldName, String searchStr, ConversionService conversionService) { TypeDescriptor descriptor = getTypeDescriptor(fieldName, entityPath); if (descriptor == null) { throw new IllegalArgumentException( String.format("Can't found field '%s' on entity '%s'", fieldName, entityPath.getType())); } Class<?> fieldType = descriptor.getType(); // Check for field type in order to delegate in custom-by-type // create expression method if (String.class == fieldType) { return createStringLikeExpression(entityPath, fieldName, searchStr); } else if (Boolean.class == fieldType || boolean.class == fieldType) { return createBooleanExpression(entityPath, fieldName, searchStr); } else if (Number.class.isAssignableFrom(fieldType) || NUMBER_PRIMITIVES.contains(fieldType)) { return createNumberExpressionGenerics(entityPath, fieldName, fieldType, descriptor, searchStr, conversionService); } else if (Date.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) { BooleanExpression expression = createDateExpression(entityPath, fieldName, (Class<Date>) fieldType, searchStr); return expression; } else if (fieldType.isEnum()) { return createEnumExpression(entityPath, fieldName, searchStr, (Class<? extends Enum>) fieldType); } return null; }
From source file:org.richfaces.tests.metamer.ftest.MatrixConfigurator.java
private List<? extends Object> getUseParameter(Class<?> testClass, Class<?> parameterType, Use useAnnotation) { List<Object> result = new LinkedList<Object>(); if (useAnnotation.empty()) { result.addAll(Arrays.asList(new Object[] { null })); }// www.j a v a2 s . c o m if (useAnnotation.ints().length > 0) { if (parameterType == int.class || parameterType == Integer.class) { result.addAll(Arrays.asList(ArrayUtils.toObject(useAnnotation.ints()))); } } if (useAnnotation.decimals().length > 0) { if (parameterType == double.class || parameterType == Double.class) { result.addAll(Arrays.asList(ArrayUtils.toObject(useAnnotation.decimals()))); } } if (useAnnotation.strings().length > 0) { if (parameterType == String.class) { result.addAll(Arrays.asList(useAnnotation.strings())); } } if (useAnnotation.booleans().length > 0) { if (parameterType == boolean.class || parameterType == Boolean.class) { result.addAll(Arrays.asList(ArrayUtils.toObject(useAnnotation.booleans()))); } } if (useAnnotation.enumeration()) { if (!parameterType.isEnum()) { throw new IllegalArgumentException(parameterType + "have to be enumeration"); } result.addAll(Arrays.asList(parameterType.getEnumConstants())); } // tries satisfy parameter from fields if (result.isEmpty()) { Object testInstance = getTestInstance(testClass); for (int i = 0; i < useAnnotation.value().length; i++) { boolean satisfied = false; String namePattern = useAnnotation.value()[i]; namePattern = StringUtils.replace(namePattern, "*", ".+"); namePattern = StringUtils.replace(namePattern, "?", "."); for (Field field : getAllFields(testClass)) { Pattern pattern = Pattern.compile(namePattern); if (pattern.matcher(field.getName()).matches()) { boolean isArray = field.getType().isArray(); Class<?> representedType = field.getType(); if (!parameterType.isAssignableFrom(representedType) && isArray) { representedType = field.getType().getComponentType(); } else { isArray = false; } if (parameterType.isAssignableFrom(representedType)) { Object[] assignments = getDeclaredFieldValues(testInstance, field, isArray); for (Object assignment : assignments) { result.add(assignment); } satisfied = true; } else { throw new IllegalStateException( "cannot satisfy parameter with declared field '" + field.getName() + "'"); } } } if (satisfied) { continue; } throw new IllegalStateException( "cannot find the field satysfying injection point with name pattern: " + useAnnotation.value()[i]); } } if (useAnnotation.useNull()) { if (parameterType.isPrimitive()) { throw new IllegalArgumentException("parameterType is primitive, can't use null value"); } if (result.contains(null)) { result.addAll(null); } } return result; }
From source file:io.stallion.reflection.PropertyUtils.java
/** * Try to transform the passed in value into the destinationClass, via a applying a boatload of * heuristics.//from w ww . j a v a2 s.c o m * * @param value * @param destinationClass * @return */ public static Object transform(Object value, Class destinationClass) { if (value == null) { return null; } if (value.getClass() == destinationClass) return value; if (destinationClass.isInstance(value)) { return value; } // If target type is Date and json was a long, convert the long to a date if (destinationClass == Date.class && (value.getClass() == long.class || value.getClass() == Long.class)) { return new Date((long) value); } // Convert integers to longs, if target type is long if ((destinationClass == Long.class || destinationClass == long.class) && (value.getClass() == int.class || value.getClass() == Integer.class)) { return new Long((int) value); } // Convert ints and longs to ZonedDateTime, if ZonedDateTime was a long if (destinationClass == ZonedDateTime.class && (value.getClass() == long.class || value.getClass() == Long.class || value.getClass() == int.class || value.getClass() == Integer.class)) { if (value.getClass() == Integer.class || value.getClass() == int.class) { return ZonedDateTime.ofInstant(Instant.ofEpochMilli(((int) value) * 1000), GeneralUtils.UTC); } else { return ZonedDateTime.ofInstant(Instant.ofEpochMilli((long) value), GeneralUtils.UTC); } } if (destinationClass == ZonedDateTime.class && value instanceof Timestamp) { return ZonedDateTime.ofInstant(((Timestamp) value).toInstant(), UTC); } if (destinationClass == Long.class && value instanceof BigInteger) { return ((BigInteger) value).longValue(); } if (destinationClass == ZonedDateTime.class && (value.getClass() == double.class || value.getClass() == Double.class)) { return ZonedDateTime.ofInstant(Instant.ofEpochMilli(Math.round((Double) value)), GeneralUtils.UTC); } // Convert Strings to Enums, if target type was an enum if (destinationClass.isEnum()) { return Enum.valueOf(destinationClass, value.toString()); } if ((destinationClass == boolean.class || destinationClass == Boolean.class)) { if (value instanceof String) { return Boolean.valueOf((String) value); } else if (value instanceof Integer) { return (Integer) value > 0; } else if (value instanceof Long) { return (Long) value > 0; } } if ((destinationClass == byte.class || destinationClass == Byte.class) && value.getClass() == String.class) { return new Byte((String) value); } if ((destinationClass == short.class || destinationClass == Short.class) && value.getClass() == String.class) { return new Short((String) value); } if ((destinationClass == int.class || destinationClass == Integer.class) && value.getClass() == String.class) { return new Integer((String) value); } if ((destinationClass == long.class || destinationClass == Long.class) && value.getClass() == String.class) { return new Long((String) value); } if ((destinationClass == long.class || destinationClass == Long.class) && value instanceof Integer) { return new Long((Integer) value); } if ((destinationClass == float.class || destinationClass == Float.class) && value.getClass() == String.class) { return new Float((String) value); } if ((destinationClass == float.class || destinationClass == Float.class) && value.getClass() == Integer.class) { return ((Integer) value).floatValue(); } if ((destinationClass == float.class || destinationClass == Float.class) && value.getClass() == Long.class) { return ((Long) value).floatValue(); } if ((destinationClass == float.class || destinationClass == Float.class) && value.getClass() == Double.class) { return ((Double) value).floatValue(); } if ((destinationClass == double.class || destinationClass == Double.class) && value.getClass() == Long.class) { return ((Long) value).floatValue(); } if ((destinationClass == float.class || destinationClass == Float.class) && value.getClass() == String.class) { return new Float((String) value); } if ((destinationClass == double.class || destinationClass == Double.class) && value.getClass() == String.class) { return new Double((String) value); } // If the type mis-match is due to boxing, just return the value if (value.getClass() == boolean.class || value.getClass() == Boolean.class || value.getClass() == byte.class || value.getClass() == Byte.class || value.getClass() == short.class || value.getClass() == Short.class || value.getClass() == int.class || value.getClass() == Integer.class || value.getClass() == long.class || value.getClass() == Long.class || value.getClass() == float.class || value.getClass() == Float.class || value.getClass() == double.class || value.getClass() == Double.class) return value; throw new PropertyException("cannot convert values of type '" + value.getClass().getName() + "' into type '" + destinationClass + "'"); }
From source file:org.bitpipeline.lib.friendlyjson.JSONEntity.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static Object fromJson(Class<?> clazz, Object json) throws JSONMappingException { if (json == null) return null; Object fromJson = null;// www . java2 s. co m if (clazz == null) { try { fromJson = JSONEntity.fromJson(json); } catch (JSONException e) { e.printStackTrace(); throw new JSONMappingException(e); } } else { Constructor<?> constructor; ; if (JSONEntity.class.isAssignableFrom(clazz)) { // A JSON Entity. Class<?> enclosingClass = clazz.getEnclosingClass(); if (enclosingClass != null && (clazz.getModifiers() & Modifier.STATIC) == 0) { // it's a non static inner class try { constructor = clazz.getDeclaredConstructor(enclosingClass, JSONObject.class); } catch (Exception e) { throw new JSONMappingException(clazz.getName() + JSONEntity.MSG_MUST_HAVE_CONSTRUCTOR, e); } try { /* we actually don't know the enclosing object... * this will be a problem with inner classes that * reference the enclosing class instance at * constructor time... although with json entities * that should not happen. */ fromJson = constructor.newInstance(null, json); } catch (Exception e) { throw new JSONMappingException(e); } } else { // static inner class try { constructor = clazz.getDeclaredConstructor(JSONObject.class); } catch (Exception e) { throw new JSONMappingException(clazz.getName() + JSONEntity.MSG_MUST_HAVE_CONSTRUCTOR, e); } try { fromJson = constructor.newInstance(json); } catch (Exception e) { throw new JSONMappingException("clazz = " + clazz.getName() + "; json = " + json.toString(), e); } } } else if (clazz.isEnum()) { try { fromJson = Enum.valueOf((Class<Enum>) clazz, json.toString()); } catch (Exception e) { fromJson = null; } } else { try { fromJson = JSONEntity.fromJson(json); } catch (JSONException e) { e.printStackTrace(); } } } if (clazz != null && !clazz.isAssignableFrom(fromJson.getClass())) throw new JSONMappingException("Was expeting a " + clazz.getName() + " but received a " + fromJson.getClass().getName() + " instead."); return fromJson; }
From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java
@Override public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type fulltype, ArgumentMatches matches) {// ww w .j a v a 2 s.com Class type = makeRawTypeIfNecessary(fulltype); if (source.isFlag()) return true; ArgumentDefinition defaultDefinition = createDefaultArgumentDefinition(source); ArgumentMatchValue value = getArgumentValue(defaultDefinition, matches); Object result; Tags tags = getArgumentTags(matches); // lets go through the types we support try { if (type.isPrimitive()) { Method valueOf = primitiveToWrapperMap.get(type).getMethod("valueOf", String.class); if (value == null) throw new MissingArgumentValueException(createDefaultArgumentDefinition(source)); result = valueOf.invoke(null, value.asString().trim()); } else if (type.isEnum()) { Object[] vals = type.getEnumConstants(); Object defaultEnumeration = null; // as we look at options, record the default option if it exists for (Object val : vals) { if (String.valueOf(val).equalsIgnoreCase(value == null ? null : value.asString())) return val; try { if (type.getField(val.toString()).isAnnotationPresent(EnumerationArgumentDefault.class)) defaultEnumeration = val; } catch (NoSuchFieldException e) { throw new ReviewedStingException( "parsing " + type.toString() + "doesn't contain the field " + val.toString()); } } // if their argument has no value (null), and there's a default, return that default for the enum value if (defaultEnumeration != null && value == null) result = defaultEnumeration; // if their argument has no value and there's no default, throw a missing argument value exception. // TODO: Clean this up so that null values never make it to this point. To fix this, we'll have to clean up the implementation of -U. else if (value == null) throw new MissingArgumentValueException(createDefaultArgumentDefinition(source)); else throw new UnknownEnumeratedValueException(createDefaultArgumentDefinition(source), value.asString()); } else if (type.equals(File.class)) { result = value == null ? null : value.asFile(); } else { Constructor ctor = type.getConstructor(String.class); result = ctor.newInstance(value == null ? null : value.asString()); } } catch (UserException e) { throw e; } catch (InvocationTargetException e) { throw new UserException.CommandLineException(String.format( "Failed to parse value %s for argument %s. This is most commonly caused by providing an incorrect data type (e.g. a double when an int is required)", value, source.field.getName())); } catch (Exception e) { throw new DynamicClassResolutionException(String.class, e); } // TODO FIXME! // WARNING: Side effect! parsingEngine.addTags(result, tags); return result; }
From source file:us.ihmc.idl.serializers.extra.JacksonInterchangeSerializer.java
@SuppressWarnings("unchecked") private <T> void write_array(ArrayNode child, T[] arr, @SuppressWarnings("rawtypes") TopicDataType dataType) { Class<?> arrayType = arr.getClass().getComponentType(); if (arrayType.isArray()) { for (int i = 0; i < arr.length; i++) { ArrayNode element = child.addArray(); if (arr[i] instanceof boolean[]) write_array((boolean[]) arr[i], element); else if (arr[i] instanceof byte[]) write_array((byte[]) arr[i], element); else if (arr[i] instanceof char[]) write_array((char[]) arr[i], element); else if (arr[i] instanceof short[]) write_array((short[]) arr[i], element); else if (arr[i] instanceof int[]) write_array((int[]) arr[i], element); else if (arr[i] instanceof long[]) write_array((long[]) arr[i], element); else if (arr[i] instanceof float[]) write_array((float[]) arr[i], element); else if (arr[i] instanceof double[]) write_array((double[]) arr[i], element); else/*from w w w . j a va 2 s . c om*/ write_array(element, (Object[]) arr[i], dataType); } } else if (arrayType.isEnum()) { for (int i = 0; i < arr.length; i++) { child.add(((Enum<?>) arr[i]).name()); } } else if (StringBuilder.class.isAssignableFrom(arrayType)) { for (int i = 0; i < arr.length; i++) { child.add(((StringBuilder) arr[i]).toString()); } } else if (dataType != null) { for (int i = 0; i < arr.length; i++) { ObjectNode element = child.addObject(); dataType.serialize(arr[i], new JacksonInterchangeSerializer(element, supportsArrays)); } } else { throw new NotImplementedException("Unexpected array type " + arrayType + ". Aborting."); } }
From source file:us.ihmc.idl.serializers.extra.JacksonInterchangeSerializer.java
@SuppressWarnings("unchecked") private <T> void read_array(T[] arr, JsonNode child, @SuppressWarnings("rawtypes") TopicDataType dataType) { if (child == null) { return;/* ww w .java 2 s . c o m*/ } Class<?> arrayType = arr.getClass().getComponentType(); if (arrayType.isArray()) { for (int i = 0; i < arr.length; i++) { JsonNode element = child.get(i); if (arr[i] instanceof boolean[]) read_array((boolean[]) arr[i], element); else if (arr[i] instanceof byte[]) read_array((byte[]) arr[i], element); else if (arr[i] instanceof char[]) read_array((char[]) arr[i], element); else if (arr[i] instanceof short[]) read_array((short[]) arr[i], element); else if (arr[i] instanceof int[]) read_array((int[]) arr[i], element); else if (arr[i] instanceof long[]) read_array((long[]) arr[i], element); else if (arr[i] instanceof float[]) read_array((float[]) arr[i], element); else if (arr[i] instanceof double[]) read_array((double[]) arr[i], element); else read_array((Object[]) arr[i], element, dataType); } } else if (arrayType.isEnum()) { Enum<?>[] enumConstants = (Enum[]) arr.getClass().getComponentType().getEnumConstants(); for (int i = 0; i < arr.length; i++) { JsonNode element = child.get(i); if (element != null) { arr[i] = (T) str2enum(enumConstants, element.asText()); } else { arr[i] = null; } } } else if (StringBuilder.class.isAssignableFrom(arrayType)) { for (int i = 0; i < arr.length; i++) { JsonNode element = child.get(i); if (element != null) { ((StringBuilder) arr[i]).setLength(0); ((StringBuilder) arr[i]).append(element.asText()); } } } else if (dataType != null) { for (int i = 0; i < arr.length; i++) { JsonNode element = child.get(i); if (element != null && element.isObject()) { dataType.deserialize(new JacksonInterchangeSerializer((ObjectNode) element, supportsArrays), arr[i]); } } } else { throw new NotImplementedException("Unexpected array type " + arrayType + ". Aborting."); } }
From source file:org.qcert.camp.translator.SemRule2CAMP.java
/** * Test whether a type is an enumeration type; if so, its translation is integer (at least for now). * @param type the type to test/*from w w w . jav a 2 s .c o m*/ * @return true if it is an an enumeration */ private boolean isEnumeration(SemType type) { if (type instanceof SemClass) { Class<?> nativeClass = ((SemClass) type).getNativeClass(); if (nativeClass != null && nativeClass.isEnum()) return true; return heuristicEnum((SemClass) type); } return false; }
From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java
private T mapResults(T instance, List results, ArrayList<String> pList) throws InstantiationException, IllegalAccessException, IllegalArgumentException { pList.parallelStream().forEach(e -> { Object o = instance;/* ww w. j a v a2 s . c o m*/ for (String fieldName : e.split("\\.")) { BeanMap m = new BeanMap(o); Class type = m.getType(fieldName); if (isRedisEntity(type)) { o = m.get(fieldName); } else { Object value; Object result = results.get(pList.indexOf(e)); if (result == null) { value = null; } else if (String.class.isAssignableFrom(type)) { value = result.toString(); } else if (type.isEnum()) { try { value = type.getMethod("valueOf", String.class).invoke(null, results.get(pList.indexOf(e))); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new IllegalArgumentException(ex); } } else if (result.getClass().isAssignableFrom(type)) { value = type.cast(result); } else { try { value = type.getConstructor(result.getClass()).newInstance(result); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new IllegalArgumentException(ex); } } m.put(fieldName, value); } } }); return instance; }
From source file:org.openengsb.core.ekb.persistence.edb.internal.EDBConverter.java
/** * Generate the value for a specific property of a model out of an EDBObject. *//*from w w w. j a va 2 s.c o m*/ private Object getValueForProperty(PropertyDescriptor propertyDescriptor, EDBObject object) { Method setterMethod = propertyDescriptor.getWriteMethod(); String propertyName = propertyDescriptor.getName(); Object value = object.getObject(propertyName); Class<?> parameterType = setterMethod.getParameterTypes()[0]; // TODO: OPENENGSB-2719 do that in a better way than just an if-else series if (Map.class.isAssignableFrom(parameterType)) { List<Class<?>> classes = getGenericMapParameterClasses(setterMethod); value = getMapValue(classes.get(0), classes.get(1), propertyName, object); } else if (List.class.isAssignableFrom(parameterType)) { Class<?> clazz = getGenericListParameterClass(setterMethod); value = getListValue(clazz, propertyName, object); } else if (value == null) { return null; } else if (OpenEngSBModel.class.isAssignableFrom(parameterType)) { EDBObject obj = edbService.getObject((String) value); value = convertEDBObjectToUncheckedModel(parameterType, obj); object.remove(propertyName); } else if (parameterType.equals(FileWrapper.class)) { FileWrapper wrapper = new FileWrapper(); String filename = object.getString(propertyName + EDBConverterUtils.FILEWRAPPER_FILENAME_SUFFIX); String content = (String) value; wrapper.setFilename(filename); wrapper.setContent(Base64.decodeBase64(content)); value = wrapper; object.remove(propertyName + EDBConverterUtils.FILEWRAPPER_FILENAME_SUFFIX); } else if (parameterType.equals(File.class)) { return null; } else if (object.containsKey(propertyName)) { if (parameterType.isEnum()) { value = getEnumValue(parameterType, value); } else if (Number.class.isAssignableFrom(parameterType)) { value = NumberUtils.createNumber((String) value); } } object.remove(propertyName); return value; }