List of usage examples for java.lang Class isEnum
public boolean isEnum()
From source file:org.apache.shindig.protocol.conversion.BeanFilter.java
/** * Provide list of all fields for a specific bean * @param bean the class to list fields for * @param depth maximum depth of recursive (mainly for infinite loop protection) *//*from ww w.java 2s . c om*/ public List<String> getBeanFields(Class<?> bean, int depth) { List<String> fields = Lists.newLinkedList(); for (Method method : bean.getMethods()) { if (method.getName().startsWith("get")) { String fieldName = method.getName().substring(3); fields.add(fieldName); Class<?> returnType = method.getReturnType(); // Get the type of list: if (List.class.isAssignableFrom(returnType)) { ParameterizedType aType = (ParameterizedType) method.getGenericReturnType(); Type[] parameterArgTypes = aType.getActualTypeArguments(); if (parameterArgTypes.length > 0) { returnType = (Class<?>) parameterArgTypes[0]; } else { returnType = null; } } // Get the type of map value if (Map.class.isAssignableFrom(returnType)) { ParameterizedType aType = (ParameterizedType) method.getGenericReturnType(); Type[] parameterArgTypes = aType.getActualTypeArguments(); if (parameterArgTypes.length > 1) { returnType = (Class<?>) parameterArgTypes[1]; } else { returnType = null; } } // Get member fields and append fields using dot notation if (depth > 1 && returnType != null && !returnType.isPrimitive() && !returnType.isEnum() && !BeanDelegator.PRIMITIVE_TYPE_CLASSES.contains(returnType)) { List<String> subFields = getBeanFields(returnType, depth - 1); for (String field : subFields) { fields.add(fieldName + DELIMITER + field); } } } } return fields; }
From source file:com.nonninz.robomodel.RoboModel.java
void saveField(Field field, TypedContentValues cv) { final Class<?> type = field.getType(); final boolean wasAccessible = field.isAccessible(); field.setAccessible(true);/* ww w . j a v a2s .c om*/ try { if (type == String.class) { cv.put(field.getName(), (String) field.get(this)); } else if (type == Boolean.TYPE) { cv.put(field.getName(), field.getBoolean(this)); } else if (type == Byte.TYPE) { cv.put(field.getName(), field.getByte(this)); } else if (type == Double.TYPE) { cv.put(field.getName(), field.getDouble(this)); } else if (type == Float.TYPE) { cv.put(field.getName(), field.getFloat(this)); } else if (type == Integer.TYPE) { cv.put(field.getName(), field.getInt(this)); } else if (type == Long.TYPE) { cv.put(field.getName(), field.getLong(this)); } else if (type == Short.TYPE) { cv.put(field.getName(), field.getShort(this)); } else if (type.isEnum()) { final Object value = field.get(this); if (value != null) { final Method method = type.getMethod("name"); final String str = (String) method.invoke(value); cv.put(field.getName(), str); } } else { // Try to JSONify it (db column must be of type text) final String json = mMapper.writeValueAsString(field.get(this)); cv.put(field.getName(), json); } } catch (final IllegalAccessException e) { final String msg = String.format("Field %s is not accessible", type, field.getName()); throw new IllegalArgumentException(msg); } catch (final JsonProcessingException e) { Ln.w(e, "Error while dumping %s of type %s to Json", field.getName(), type); final String msg = String.format("Field %s is not accessible", type, field.getName()); throw new IllegalArgumentException(msg); } catch (final NoSuchMethodException e) { // Should not happen throw new RuntimeException(e); } catch (final InvocationTargetException e) { // Should not happen throw new RuntimeException(e); } finally { field.setAccessible(wasAccessible); } }
From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java
private FieldModel createField(String name, Class type, boolean required, EntityModel entityModel) { FieldModel fieldModel = new FieldModel(); fieldModel.setName(StringUtils.uncapitalize(name)); fieldModel.setPath(entityModel.getLookup()); fieldModel.setLookup(DiffUtils.lookup(entityModel.getLookup(), name)); fieldModel.setDisplayName(StringUtils.capitalize(name)); fieldModel.setRequired(required);//from w w w .j a va 2s . c om fieldModel.setParent(entityModel); if (type.isEnum()) { Enum[] enumConstants = (Enum[]) type.getEnumConstants(); fieldModel.setFieldType(LONG_TEXT); AllowedFieldValueList valueList = new AllowedFieldValueList(); for (Enum enumConstant : enumConstants) valueList.add(enumConstant.name()); fieldModel.setAllowedFieldValueList(valueList); } else { fieldModel.setFieldType(convert(type)); } return fieldModel; }
From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java
private Object instantiate(Class<?> customSerializer, Class<?> instanceClass) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SerializationException { if (customSerializer != null) { for (Method method : customSerializer.getMethods()) { if ("instantiate".equals(method.getName())) { return method.invoke(null, this); }// ww w .j av a 2s .co m } // Ok to not have one. } if (instanceClass.isArray()) { int length = readInt(); // We don't pre-allocate the array; this prevents an allocation attack return new BoundedList<Object>(instanceClass.getComponentType(), length); } else if (instanceClass.isEnum()) { Enum<?>[] enumConstants = (Enum[]) instanceClass.getEnumConstants(); int ordinal = readInt(); assert (ordinal >= 0 && ordinal < enumConstants.length); return enumConstants[ordinal]; } else { Constructor<?> constructor = instanceClass.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } }
From source file:org.eobjects.analyzer.util.convert.StandardTypeConverter.java
@Override public Object fromString(Class<?> type, String str) { if (ReflectionUtils.isString(type)) { return str; }//from ww w . j a v a 2s . c o m if (ReflectionUtils.isBoolean(type)) { return Boolean.valueOf(str); } if (ReflectionUtils.isCharacter(type)) { return Character.valueOf(str.charAt(0)); } if (ReflectionUtils.isInteger(type)) { return Integer.valueOf(str); } if (ReflectionUtils.isLong(type)) { return Long.valueOf(str); } if (ReflectionUtils.isByte(type)) { return Byte.valueOf(str); } if (ReflectionUtils.isShort(type)) { return Short.valueOf(str); } if (ReflectionUtils.isDouble(type)) { return Double.valueOf(str); } if (ReflectionUtils.isFloat(type)) { return Float.valueOf(str); } if (ReflectionUtils.is(type, Class.class)) { try { return Class.forName(str); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Class not found: " + str, e); } } if (type.isEnum()) { try { Object[] enumConstants = type.getEnumConstants(); // first look for enum constant matches Method nameMethod = Enum.class.getMethod("name"); for (Object e : enumConstants) { String name = (String) nameMethod.invoke(e); if (name.equals(str)) { return e; } } // check for aliased enums for (Object e : enumConstants) { String name = (String) nameMethod.invoke(e); Field field = type.getField(name); Alias alias = ReflectionUtils.getAnnotation(field, Alias.class); if (alias != null) { String[] aliasValues = alias.value(); for (String aliasValue : aliasValues) { if (aliasValue.equals(str)) { return e; } } } } } catch (Exception e) { throw new IllegalStateException("Unexpected error occurred while examining enum", e); } throw new IllegalArgumentException("No such enum '" + str + "' in enum class: " + type.getName()); } if (ReflectionUtils.isDate(type)) { return toDate(str); } if (ReflectionUtils.is(type, File.class)) { return new File(str.replace('\\', File.separatorChar)); } if (ReflectionUtils.is(type, Calendar.class)) { Date date = toDate(str); Calendar c = Calendar.getInstance(); c.setTime(date); return c; } if (ReflectionUtils.is(type, Pattern.class)) { try { return Pattern.compile(str); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("Invalid regular expression syntax in '" + str + "'.", e); } } if (ReflectionUtils.is(type, java.sql.Date.class)) { Date date = toDate(str); return new java.sql.Date(date.getTime()); } if (ReflectionUtils.isNumber(type)) { return ConvertToNumberTransformer.transformValue(str); } if (ReflectionUtils.is(type, Serializable.class)) { logger.warn("fromString(...): No built-in handling of type: {}, using deserialization", type.getName()); byte[] bytes = (byte[]) parentConverter.fromString(byte[].class, str); ChangeAwareObjectInputStream objectInputStream = null; try { objectInputStream = new ChangeAwareObjectInputStream(new ByteArrayInputStream(bytes)); objectInputStream.addClassLoader(type.getClassLoader()); Object obj = objectInputStream.readObject(); return obj; } catch (Exception e) { throw new IllegalStateException("Could not deserialize to " + type + ".", e); } finally { FileHelper.safeClose(objectInputStream); } } throw new IllegalArgumentException("Could not convert to type: " + type.getName()); }
From source file:com.vmware.photon.controller.deployer.helpers.TestHelper.java
public static Object[][] getInvalidStageTransitions(@Nullable Class<? extends Enum> subStages) { if (subStages == null) { ///*from www . j ava 2s . c om*/ // N.B. Tasks without sub-stages must reject these default stage transitions. // return new Object[][] { { TaskState.TaskStage.CREATED, TaskState.TaskStage.CREATED }, { TaskState.TaskStage.STARTED, TaskState.TaskStage.CREATED }, { TaskState.TaskStage.FINISHED, TaskState.TaskStage.CREATED }, { TaskState.TaskStage.FINISHED, TaskState.TaskStage.STARTED }, { TaskState.TaskStage.FINISHED, TaskState.TaskStage.FINISHED }, { TaskState.TaskStage.FINISHED, TaskState.TaskStage.FAILED }, { TaskState.TaskStage.FINISHED, TaskState.TaskStage.CANCELLED }, { TaskState.TaskStage.FAILED, TaskState.TaskStage.CREATED }, { TaskState.TaskStage.FAILED, TaskState.TaskStage.STARTED }, { TaskState.TaskStage.FAILED, TaskState.TaskStage.FINISHED }, { TaskState.TaskStage.FAILED, TaskState.TaskStage.FAILED }, { TaskState.TaskStage.FAILED, TaskState.TaskStage.CANCELLED }, { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.CREATED }, { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.STARTED }, { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FINISHED }, { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED }, { TaskState.TaskStage.CANCELLED, TaskState.TaskStage.CANCELLED }, }; } if (!subStages.isEnum() || subStages.getEnumConstants().length == 0) { throw new IllegalStateException("Class " + subStages.getName() + " is not a valid enum"); } List<Object[]> invalidStageTransitions = new ArrayList<>(); invalidStageTransitions .add(new Object[] { TaskState.TaskStage.CREATED, null, TaskState.TaskStage.CREATED, null }); Enum[] enumConstants = subStages.getEnumConstants(); for (int i = 0; i < enumConstants.length; i++) { invalidStageTransitions.add(new Object[] { TaskState.TaskStage.STARTED, enumConstants[i], TaskState.TaskStage.CREATED, null }); for (int j = 0; j < i; j++) { invalidStageTransitions.add(new Object[] { TaskState.TaskStage.STARTED, enumConstants[i], TaskState.TaskStage.STARTED, enumConstants[j] }); } } invalidStageTransitions .add(new Object[] { TaskState.TaskStage.FINISHED, null, TaskState.TaskStage.CREATED, null }); for (int i = 0; i < enumConstants.length; i++) { invalidStageTransitions.add(new Object[] { TaskState.TaskStage.FINISHED, null, TaskState.TaskStage.STARTED, enumConstants[i] }); } invalidStageTransitions .add(new Object[] { TaskState.TaskStage.FINISHED, null, TaskState.TaskStage.FINISHED, null }); invalidStageTransitions .add(new Object[] { TaskState.TaskStage.FINISHED, null, TaskState.TaskStage.FAILED, null }); invalidStageTransitions .add(new Object[] { TaskState.TaskStage.FINISHED, null, TaskState.TaskStage.CANCELLED, null }); invalidStageTransitions .add(new Object[] { TaskState.TaskStage.FAILED, null, TaskState.TaskStage.CREATED, null }); for (int i = 0; i < enumConstants.length; i++) { invalidStageTransitions.add(new Object[] { TaskState.TaskStage.FAILED, null, TaskState.TaskStage.STARTED, enumConstants[i] }); } invalidStageTransitions .add(new Object[] { TaskState.TaskStage.FAILED, null, TaskState.TaskStage.FINISHED, null }); invalidStageTransitions .add(new Object[] { TaskState.TaskStage.FAILED, null, TaskState.TaskStage.FAILED, null }); invalidStageTransitions .add(new Object[] { TaskState.TaskStage.FAILED, null, TaskState.TaskStage.CANCELLED, null }); invalidStageTransitions .add(new Object[] { TaskState.TaskStage.CANCELLED, null, TaskState.TaskStage.CREATED, null }); for (int i = 0; i < enumConstants.length; i++) { invalidStageTransitions.add(new Object[] { TaskState.TaskStage.CANCELLED, null, TaskState.TaskStage.STARTED, enumConstants[i] }); } invalidStageTransitions .add(new Object[] { TaskState.TaskStage.CANCELLED, null, TaskState.TaskStage.FINISHED, null }); invalidStageTransitions .add(new Object[] { TaskState.TaskStage.CANCELLED, null, TaskState.TaskStage.FAILED, null }); invalidStageTransitions .add(new Object[] { TaskState.TaskStage.CANCELLED, null, TaskState.TaskStage.CANCELLED, null }); Object[][] returnValue = new Object[invalidStageTransitions.size()][4]; for (int i = 0; i < invalidStageTransitions.size(); i++) { returnValue[i][0] = invalidStageTransitions.get(i)[0]; returnValue[i][1] = invalidStageTransitions.get(i)[1]; returnValue[i][2] = invalidStageTransitions.get(i)[2]; returnValue[i][3] = invalidStageTransitions.get(i)[3]; } return returnValue; }
From source file:org.bimserver.tools.generators.ProtocolBuffersGenerator.java
private String createMessage(StringBuilder sb, SClass sType) { if (sType == null) { return "VoidResponse"; }/*from w w w . jav a 2s . c o m*/ Class<?> clazz = sType.getInstanceClass(); if (generatedClasses.containsKey(clazz)) { return generatedClasses.get(clazz); } if (clazz == Class.class) { return "string"; } else if (clazz == boolean.class || clazz == Boolean.class) { return "bool"; } else if (clazz == Long.class || clazz == long.class) { return "int64"; } else if (clazz == Date.class) { return "int64"; } else if (clazz == DataHandler.class || clazz == byte[].class) { return "bytes"; } else if (clazz == Integer.class | clazz == int.class) { return "int32"; } else if (clazz == Float.class | clazz == float.class) { return "float"; } else if (clazz == Double.class | clazz == double.class) { return "double"; } else if (clazz.isEnum()) { return createEnum(sb, clazz); } else if (sType.isString()) { return "string"; } else { StringBuilder messageBuilder = new StringBuilder(); SClass sClass = (SClass) sType; generatedClasses.put(clazz, clazz.getSimpleName()); messageBuilder.append("message " + clazz.getSimpleName() + " {\n"); int counter = 1; if (!sClass.getSubClasses().isEmpty()) { messageBuilder.append("\trequired string __actual_type = " + (counter++) + ";\n"); for (SClass subClass : sClass.getSubClasses()) { messageBuilder.append("\t"); messageBuilder.append("optional "); messageBuilder.append(createMessage(sb, subClass) + " __" + subClass.getInstanceClass().getSimpleName() + " = " + (counter++) + ";\n"); } } for (SField field : sClass.getFields()) { messageBuilder.append("\t"); if (field.isAggregate()) { messageBuilder.append("repeated "); } else { messageBuilder.append("optional "); } SClass type = field.getType(); if (field.isAggregate()) { type = field.getGenericType(); // Type genericReturnType = method.getGenericReturnType(); // if (genericReturnType instanceof ParameterizedType) { // ParameterizedType parameterizedTypeImpl = // (ParameterizedType)genericReturnType; // Type type2 = // parameterizedTypeImpl.getActualTypeArguments()[0]; // parameterType = ((Class<?>)type2); // } } messageBuilder .append(createMessage(sb, type) + " " + field.getName() + " = " + (counter++) + ";\n"); } messageBuilder.append("}\n\n"); sb.append(messageBuilder); return clazz.getSimpleName(); } }
From source file:com.l2jfree.config.L2Properties.java
@SuppressWarnings("unchecked") public Object getProperty(Class<?> expectedType, ConfigProperty configProperty) { final String name = configProperty.name(); final String defaultValue = configProperty.value(); if (expectedType == Boolean.class || expectedType == Boolean.TYPE) { return getBool(name, defaultValue); } else if (expectedType == Long.class || expectedType == Long.TYPE) { return getLong(name, defaultValue); } else if (expectedType == Integer.class || expectedType == Integer.TYPE) { return getInteger(name, defaultValue); } else if (expectedType == Short.class || expectedType == Short.TYPE) { return getShort(name, defaultValue); } else if (expectedType == Byte.class || expectedType == Byte.TYPE) { return getByte(name, defaultValue); } else if (expectedType == Double.class || expectedType == Double.TYPE) { return getDouble(name, defaultValue); } else if (expectedType == Float.class || expectedType == Float.TYPE) { return getFloat(name, defaultValue); } else if (expectedType == String.class) { return getString(name, defaultValue); } else if (expectedType.isEnum()) { return getEnum(name, (Class<? extends Enum>) expectedType, defaultValue); } else {//from w ww .java2s . c o m throw new IllegalStateException(); } }
From source file:streamflow.model.generator.RandomGenerator.java
public static <T, V, W> T randomObject(Class<T> objectClass, Class<V> typeClass1, Class<W> typeClass2) { T object = null;/*from w w w . j av a2 s .co m*/ try { if (boolean.class.isAssignableFrom(objectClass) || Boolean.class.isAssignableFrom(objectClass)) { object = (T) randomBoolean(); } else if (byte.class.isAssignableFrom(objectClass) || Byte.class.isAssignableFrom(objectClass)) { object = (T) randomByte(); } else if (char.class.isAssignableFrom(objectClass) || Character.class.isAssignableFrom(objectClass)) { object = (T) randomChar(); } else if (short.class.isAssignableFrom(objectClass) || Short.class.isAssignableFrom(objectClass)) { object = (T) randomShort(); } else if (int.class.isAssignableFrom(objectClass) || Integer.class.isAssignableFrom(objectClass)) { object = (T) randomInt(); } else if (long.class.isAssignableFrom(objectClass) || Long.class.isAssignableFrom(objectClass)) { object = (T) randomLong(); } else if (float.class.isAssignableFrom(objectClass) || Float.class.isAssignableFrom(objectClass)) { object = (T) randomFloat(); } else if (double.class.isAssignableFrom(objectClass) || Double.class.isAssignableFrom(objectClass)) { object = (T) randomDouble(); } else if (String.class.isAssignableFrom(objectClass)) { object = (T) randomString(); } else if (Date.class.isAssignableFrom(objectClass)) { object = (T) randomDate(); } else if (Map.class.isAssignableFrom(objectClass)) { object = (T) randomMap((Class<Map>) objectClass, typeClass1, typeClass2); } else if (List.class.isAssignableFrom(objectClass)) { object = (T) randomList((Class<List>) objectClass, typeClass1); } else if (Set.class.isAssignableFrom(objectClass)) { object = (T) randomSet((Class<Set>) objectClass, typeClass1); } else if (Collection.class.isAssignableFrom(objectClass)) { object = (T) randomCollection((Class<Collection>) objectClass, typeClass1); } else if (objectClass.isArray()) { object = (T) randomArray(objectClass.getComponentType()); } else if (objectClass.isEnum()) { object = (T) randomEnum(objectClass); } else { object = objectClass.newInstance(); for (Field field : objectClass.getDeclaredFields()) { if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) { Class fieldType = field.getType(); field.setAccessible(true); if (field.getGenericType() instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) field.getGenericType(); Type[] typeArgs = paramType.getActualTypeArguments(); if (typeArgs.length == 1) { if (typeArgs[0] instanceof ParameterizedType) { // TODO: HANDLE NESTED PARAM TYPE } else { field.set(object, randomObject(fieldType, (Class<?>) typeArgs[0])); } } else if (typeArgs.length == 2) { field.set(object, randomObject(fieldType, (Class<?>) typeArgs[0], (Class<?>) typeArgs[1])); } } else { field.set(object, randomObject(fieldType)); } } } } } catch (Exception ex) { //LOG.error("Exception while building the random object", ex); } return object; }
From source file:gov.nih.nci.system.web.struts.action.UpdateAction.java
public Object convertValue(Class klass, Object value) throws Exception { String fieldType = klass.getName(); Object convertedValue = null; try {/*from ww w . ja v a 2s . co m*/ if (fieldType.equals("java.lang.Long")) { convertedValue = new Long((String) value); } else if (fieldType.equals("java.lang.Integer")) { convertedValue = new Integer((String) value); } else if (fieldType.equals("java.lang.String")) { convertedValue = value; } else if (fieldType.equals("java.lang.Float")) { convertedValue = new Float((String) value); } else if (fieldType.equals("java.lang.Double")) { convertedValue = new Double((String) value); } else if (fieldType.equals("java.lang.Boolean")) { convertedValue = new Boolean((String) value); } else if (fieldType.equals("java.util.Date")) { SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy"); convertedValue = format.parse((String) value); } else if (fieldType.equals("java.net.URI")) { convertedValue = new URI((String) value); } else if (fieldType.equals("java.lang.Character")) { convertedValue = new Character(((String) value).charAt(0)); } else if (klass.isEnum()) { Class enumKlass = Class.forName(fieldType); convertedValue = Enum.valueOf(enumKlass, (String) value); } else { throw new Exception("type mismatch - " + fieldType); } } catch (NumberFormatException e) { e.printStackTrace(); throw new Exception(e.getMessage()); } catch (Exception ex) { log.error("ERROR : " + ex.getMessage()); throw ex; } return convertedValue; }