Example usage for java.lang Class isEnum

List of usage examples for java.lang Class isEnum

Introduction

In this page you can find the example usage for java.lang Class isEnum.

Prototype

public boolean isEnum() 

Source Link

Document

Returns true if and only if this class was declared as an enum in the source code.

Usage

From source file:com.alibaba.fastjson.parser.ParserConfig.java

public ObjectDeserializer createJavaBeanDeserializer(Class<?> clazz, Type type) {
    boolean asmEnable = this.asmEnable & !this.fieldBased;
    if (asmEnable) {
        JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class);

        if (jsonType != null) {
            Class<?> deserializerClass = jsonType.deserializer();
            if (deserializerClass != Void.class) {
                try {
                    Object deseralizer = deserializerClass.newInstance();
                    if (deseralizer instanceof ObjectDeserializer) {
                        return (ObjectDeserializer) deseralizer;
                    }//www  . jav a2s.c om
                } catch (Throwable e) {
                    // skip
                }
            }

            asmEnable = jsonType.asm();
        }

        if (asmEnable) {
            Class<?> superClass = JavaBeanInfo.getBuilderClass(clazz, jsonType);
            if (superClass == null) {
                superClass = clazz;
            }

            for (;;) {
                if (!Modifier.isPublic(superClass.getModifiers())) {
                    asmEnable = false;
                    break;
                }

                superClass = superClass.getSuperclass();
                if (superClass == Object.class || superClass == null) {
                    break;
                }
            }
        }
    }

    if (clazz.getTypeParameters().length != 0) {
        asmEnable = false;
    }

    if (asmEnable && asmFactory != null && asmFactory.classLoader.isExternalClass(clazz)) {
        asmEnable = false;
    }

    if (asmEnable) {
        asmEnable = ASMUtils.checkName(clazz.getSimpleName());
    }

    if (asmEnable) {
        if (clazz.isInterface()) {
            asmEnable = false;
        }
        JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy);

        if (asmEnable && beanInfo.fields.length > 200) {
            asmEnable = false;
        }

        Constructor<?> defaultConstructor = beanInfo.defaultConstructor;
        if (asmEnable && defaultConstructor == null && !clazz.isInterface()) {
            asmEnable = false;
        }

        for (FieldInfo fieldInfo : beanInfo.fields) {
            if (fieldInfo.getOnly) {
                asmEnable = false;
                break;
            }

            Class<?> fieldClass = fieldInfo.fieldClass;
            if (!Modifier.isPublic(fieldClass.getModifiers())) {
                asmEnable = false;
                break;
            }

            if (fieldClass.isMemberClass() && !Modifier.isStatic(fieldClass.getModifiers())) {
                asmEnable = false;
                break;
            }

            if (fieldInfo.getMember() != null //
                    && !ASMUtils.checkName(fieldInfo.getMember().getName())) {
                asmEnable = false;
                break;
            }

            JSONField annotation = fieldInfo.getAnnotation();
            if (annotation != null //
                    && ((!ASMUtils.checkName(annotation.name())) //
                            || annotation.format().length() != 0 //
                            || annotation.deserializeUsing() != Void.class //
                            || annotation.unwrapped())
                    || (fieldInfo.method != null && fieldInfo.method.getParameterTypes().length > 1)) {
                asmEnable = false;
                break;
            }

            if (fieldClass.isEnum()) { // EnumDeserializer
                ObjectDeserializer fieldDeser = this.getDeserializer(fieldClass);
                if (!(fieldDeser instanceof EnumDeserializer)) {
                    asmEnable = false;
                    break;
                }
            }
        }
    }

    if (asmEnable) {
        if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) {
            asmEnable = false;
        }
    }

    if (!asmEnable) {
        return new JavaBeanDeserializer(this, clazz, type);
    }

    JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy);
    try {
        return asmFactory.createJavaBeanDeserializer(this, beanInfo);
        // } catch (VerifyError e) {
        // e.printStackTrace();
        // return new JavaBeanDeserializer(this, clazz, type);
    } catch (NoSuchMethodException ex) {
        return new JavaBeanDeserializer(this, clazz, type);
    } catch (JSONException asmError) {
        return new JavaBeanDeserializer(this, beanInfo);
    } catch (Exception e) {
        throw new JSONException("create asm deserializer error, " + clazz.getName(), e);
    }
}

From source file:org.apache.syncope.client.console.panels.BeanPanel.java

public BeanPanel(final String id, final IModel<T> bean,
        final Map<String, Pair<AbstractFiqlSearchConditionBuilder, List<SearchClause>>> sCondWrapper,
        final String... excluded) {
    super(id, bean);
    setOutputMarkupId(true);/*  w  w w  .ja  va2  s.c o  m*/

    this.sCondWrapper = sCondWrapper;

    this.excluded = new ArrayList<>(Arrays.asList(excluded));
    this.excluded.add("serialVersionUID");
    this.excluded.add("class");

    final LoadableDetachableModel<List<String>> model = new LoadableDetachableModel<List<String>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override
        protected List<String> load() {
            final List<String> result = new ArrayList<>();

            if (BeanPanel.this.getDefaultModelObject() != null) {
                ReflectionUtils.doWithFields(BeanPanel.this.getDefaultModelObject().getClass(),
                        new FieldCallback() {

                            public void doWith(final Field field)
                                    throws IllegalArgumentException, IllegalAccessException {
                                result.add(field.getName());
                            }

                        }, new FieldFilter() {

                            public boolean matches(final Field field) {
                                return !BeanPanel.this.excluded.contains(field.getName());
                            }
                        });
            }
            return result;
        }
    };

    add(new ListView<String>("propView", model) {

        private static final long serialVersionUID = 9101744072914090143L;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        protected void populateItem(final ListItem<String> item) {
            final String fieldName = item.getModelObject();

            item.add(new Label("fieldName", new ResourceModel(fieldName, fieldName)));

            Field field = ReflectionUtils.findField(bean.getObject().getClass(), fieldName);

            if (field == null) {
                return;
            }

            final SearchCondition scondAnnot = field.getAnnotation(SearchCondition.class);
            final Schema schemaAnnot = field.getAnnotation(Schema.class);

            BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean.getObject());

            Panel panel;

            if (scondAnnot != null) {
                final String fiql = (String) wrapper.getPropertyValue(fieldName);

                final List<SearchClause> clauses;
                if (StringUtils.isEmpty(fiql)) {
                    clauses = new ArrayList<>();
                } else {
                    clauses = SearchUtils.getSearchClauses(fiql);
                }

                final AbstractFiqlSearchConditionBuilder builder;

                switch (scondAnnot.type()) {
                case "USER":
                    panel = new UserSearchPanel.Builder(new ListModel<>(clauses)).required(false)
                            .build("value");
                    builder = SyncopeClient.getUserSearchConditionBuilder();
                    break;
                case "GROUP":
                    panel = new GroupSearchPanel.Builder(new ListModel<>(clauses)).required(false)
                            .build("value");
                    builder = SyncopeClient.getGroupSearchConditionBuilder();
                    break;
                default:
                    panel = new AnyObjectSearchPanel.Builder(scondAnnot.type(), new ListModel<>(clauses))
                            .required(false).build("value");
                    builder = SyncopeClient.getAnyObjectSearchConditionBuilder(null);
                }

                if (BeanPanel.this.sCondWrapper != null) {
                    BeanPanel.this.sCondWrapper.put(fieldName, Pair.of(builder, clauses));
                }
            } else if (List.class.equals(field.getType())) {
                Class<?> listItemType = String.class;
                if (field.getGenericType() instanceof ParameterizedType) {
                    listItemType = (Class<?>) ((ParameterizedType) field.getGenericType())
                            .getActualTypeArguments()[0];
                }

                if (listItemType.equals(String.class) && schemaAnnot != null) {
                    SchemaRestClient schemaRestClient = new SchemaRestClient();

                    final List<AbstractSchemaTO> choices = new ArrayList<>();

                    for (SchemaType type : schemaAnnot.type()) {
                        switch (type) {
                        case PLAIN:
                            choices.addAll(
                                    schemaRestClient.getSchemas(SchemaType.PLAIN, schemaAnnot.anyTypeKind()));
                            break;

                        case DERIVED:
                            choices.addAll(
                                    schemaRestClient.getSchemas(SchemaType.DERIVED, schemaAnnot.anyTypeKind()));
                            break;

                        case VIRTUAL:
                            choices.addAll(
                                    schemaRestClient.getSchemas(SchemaType.VIRTUAL, schemaAnnot.anyTypeKind()));
                            break;

                        default:
                        }
                    }

                    panel = new AjaxPalettePanel.Builder<>().setName(fieldName)
                            .build("value", new PropertyModel<>(bean.getObject(), fieldName), new ListModel<>(
                                    choices.stream().map(EntityTO::getKey).collect(Collectors.toList())))
                            .hideLabel();
                } else if (listItemType.isEnum()) {
                    panel = new AjaxPalettePanel.Builder<>().setName(fieldName)
                            .build("value", new PropertyModel<>(bean.getObject(), fieldName),
                                    new ListModel(Arrays.asList(listItemType.getEnumConstants())))
                            .hideLabel();
                } else {
                    panel = new MultiFieldPanel.Builder<>(new PropertyModel<>(bean.getObject(), fieldName))
                            .build("value", fieldName,
                                    buildSinglePanel(bean.getObject(), field.getType(), fieldName, "panel"))
                            .hideLabel();
                }
            } else {
                panel = buildSinglePanel(bean.getObject(), field.getType(), fieldName, "value").hideLabel();
            }

            item.add(panel.setRenderBodyOnly(true));
        }

    }.setReuseItems(true).setOutputMarkupId(true));
}

From source file:com.espertech.esper.epl.variable.VariableServiceImpl.java

public void createNewVariable(String variableName, String variableType, Object value, boolean constant,
        boolean array, StatementExtensionSvcContext extensionServicesContext,
        EngineImportService engineImportService) throws VariableExistsException, VariableTypeException {
    // Determime the variable type
    Class type = JavaClassHelper.getClassForSimpleName(variableType);
    Class arrayType = null;//from  ww  w.j av  a  2  s .c o m
    EventType eventType = null;
    if (type == null) {
        if (variableType.toLowerCase().equals("object")) {
            type = Object.class;
        }
        if (type == null) {
            eventType = eventAdapterService.getExistsTypeByName(variableType);
            if (eventType != null) {
                type = eventType.getUnderlyingType();
            }
        }
        if (type == null) {
            try {
                type = engineImportService.resolveClass(variableType);
                if (array) {
                    arrayType = JavaClassHelper.getArrayType(type);
                }
            } catch (EngineImportException e) {
                log.debug("Not found '" + type + "': " + e.getMessage(), e);
                // expected
            }
        }
        if (type == null) {
            throw new VariableTypeException("Cannot create variable '" + variableName + "', type '"
                    + variableType + "' is not a recognized type");
        }
        if (array && eventType != null) {
            throw new VariableTypeException("Cannot create variable '" + variableName + "', type '"
                    + variableType + "' cannot be declared as an array type");
        }
    } else {
        if (array) {
            arrayType = JavaClassHelper.getArrayType(type);
        }
    }

    if ((eventType == null) && (!JavaClassHelper.isJavaBuiltinDataType(type)) && (type != Object.class)
            && !type.isArray() && !type.isEnum()) {
        if (array) {
            throw new VariableTypeException("Cannot create variable '" + variableName + "', type '"
                    + variableType + "' cannot be declared as an array, only scalar types can be array");
        }
        eventType = eventAdapterService.addBeanType(type.getName(), type, false, false, false);
    }

    if (arrayType != null) {
        type = arrayType;
    }
    createNewVariable(variableName, type, eventType, value, constant, extensionServicesContext);
}

From source file:org.cloudata.core.common.io.CObjectWritable.java

/** Write a {@link CWritable}, {@link String}, primitive type, or an array of
 * the preceding. *//*  ww w . j ava  2 s.  co  m*/
public static void writeObject(DataOutput out, Object instance, Class declaredClass, CloudataConf conf,
        boolean arrayComponent) throws IOException {

    if (instance == null) { // null
        instance = new NullInstance(declaredClass, conf);
        declaredClass = CWritable.class;
        arrayComponent = false;
    }

    if (!arrayComponent) {
        CUTF8.writeString(out, declaredClass.getName()); // always write declared
        //System.out.println("Write:declaredClass.getName():" + declaredClass.getName());
    }

    if (declaredClass.isArray()) { // array
        int length = Array.getLength(instance);
        out.writeInt(length);
        //System.out.println("Write:length:" + length);

        if (declaredClass.getComponentType() == Byte.TYPE) {
            out.write((byte[]) instance);
        } else if (declaredClass.getComponentType() == ColumnValue.class) {
            //ColumnValue?  Deserialize? ?? ?   ?? ?  .
            writeColumnValue(out, instance, declaredClass, conf, length);
        } else {
            for (int i = 0; i < length; i++) {
                writeObject(out, Array.get(instance, i), declaredClass.getComponentType(), conf,
                        !declaredClass.getComponentType().isArray());
            }
        }
    } else if (declaredClass == String.class) { // String
        CUTF8.writeString(out, (String) instance);

    } else if (declaredClass.isPrimitive()) { // primitive type

        if (declaredClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instance).booleanValue());
        } else if (declaredClass == Character.TYPE) { // char
            out.writeChar(((Character) instance).charValue());
        } else if (declaredClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instance).byteValue());
        } else if (declaredClass == Short.TYPE) { // short
            out.writeShort(((Short) instance).shortValue());
        } else if (declaredClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instance).intValue());
        } else if (declaredClass == Long.TYPE) { // long
            out.writeLong(((Long) instance).longValue());
        } else if (declaredClass == Float.TYPE) { // float
            out.writeFloat(((Float) instance).floatValue());
        } else if (declaredClass == Double.TYPE) { // double
            out.writeDouble(((Double) instance).doubleValue());
        } else if (declaredClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }
    } else if (declaredClass.isEnum()) { // enum
        CUTF8.writeString(out, ((Enum) instance).name());
    } else if (CWritable.class.isAssignableFrom(declaredClass)) { // Writable
        if (instance.getClass() == declaredClass) {
            out.writeShort(TYPE_SAME); // ? ?? ? ?? 
            //System.out.println("Write:TYPE_SAME:" + TYPE_SAME);

        } else {
            out.writeShort(TYPE_DIFF);
            //System.out.println("Write:TYPE_DIFF:" + TYPE_DIFF);
            CUTF8.writeString(out, instance.getClass().getName());
            //System.out.println("Write:instance.getClass().getName():" + instance.getClass().getName());
        }
        ((CWritable) instance).write(out);
        //System.out.println("Write:instance value");

    } else {
        throw new IOException("Can't write: " + instance + " as " + declaredClass);
    }
}

From source file:org.gvnix.web.datatables.util.QuerydslUtils.java

/**
 * Utility for constructing where clause expressions.
 * //  w  w  w .j a  v  a2s.  c o  m
 * @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, MessageSource messageSource) {

    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 createStringExpressionWithOperators(entityPath, fieldName, searchStr, conversionService,
                messageSource);
    } else if (Boolean.class == fieldType || boolean.class == fieldType) {
        return createBooleanExpressionWithOperators(entityPath, fieldName, searchStr, conversionService,
                messageSource);
    } else if (Number.class.isAssignableFrom(fieldType) || NUMBER_PRIMITIVES.contains(fieldType)) {
        return createNumberExpressionGenericsWithOperators(entityPath, fieldName, descriptor, searchStr,
                conversionService, messageSource);
    } else if (Date.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) {
        String datePattern = "dd/MM/yyyy";
        if (messageSource != null) {
            datePattern = messageSource.getMessage("global.filters.operations.date.pattern", null,
                    LocaleContextHolder.getLocale());
        }
        BooleanExpression expression = createDateExpressionWithOperators(entityPath, fieldName,
                (Class<Date>) fieldType, searchStr, conversionService, messageSource, datePattern);
        return expression;
    }

    else if (fieldType.isEnum()) {
        return createEnumExpression(entityPath, fieldName, searchStr, (Class<? extends Enum>) fieldType);
    }
    return null;
}

From source file:de.javakaffee.web.msm.serializer.javolution.XMLBinding.java

@SuppressWarnings("unchecked")
public <T> XMLFormat<T> getFormat(final Class<? extends T> cls) {
    XMLFormat<?> xmlFormat = _formats.get(cls);
    if (xmlFormat != null) {
        return (XMLFormat<T>) xmlFormat;
    }/*w  ww  .  j av  a2s.  c o m*/

    //        //System.out.println( "got format " + format + " for class " +  cls);
    //        if ( cls.isPrimitive() || cls.equals( String.class ) || Number.class.isAssignableFrom( cls )
    //                || Map.class.isAssignableFrom( cls ) || Collection.class.isAssignableFrom( cls ) )
    //            return format;
    if (cls == Boolean.class) {
        return (XMLFormat<T>) XML_BOOLEAN;
    } else if (cls == String.class) {
        return (XMLFormat<T>) XML_STRING;
    } else if (cls == Character.class) {
        return (XMLFormat<T>) XML_CHARACTER;
    } else if (cls == Byte.class) {
        return (XMLFormat<T>) XML_BYTE;
    } else if (cls == Short.class) {
        return (XMLFormat<T>) XML_SHORT;
    } else if (cls == Integer.class) {
        return (XMLFormat<T>) XML_INTEGER;
    } else if (cls == Long.class) {
        return (XMLFormat<T>) XML_LONG;
    } else if (cls == Float.class) {
        return (XMLFormat<T>) XML_FLOAT;
    } else if (cls == Double.class) {
        return (XMLFormat<T>) XML_DOUBLE;
    }
    if (cls.isArray()) {
        return getArrayFormat(cls);
    } else if (cls.isEnum()) {
        return (XMLFormat<T>) ENUM_FORMAT;
    } else if (Collection.class.isAssignableFrom(cls)) {
        return (XMLFormat<T>) XMLCollectionFormat;
    } else if (Map.class.isAssignableFrom(cls)) {
        return (XMLFormat<T>) XMLMapFormat;
    } else if (cls == Class.class) {
        return (XMLFormat<T>) XML_CLASS;
    } else if (Calendar.class.isAssignableFrom(cls)) {
        return (XMLFormat<T>) XML_CALENDAR;
    } else {
        if (xmlFormat == null) {
            if (XMLReflectionFormat.isNumberFormat(cls)) {
                xmlFormat = XMLReflectionFormat.getNumberFormat(cls);
            } else {
                xmlFormat = new XMLReflectionFormat(cls);
            }
            _formats.put(cls, xmlFormat);
        }
        return (XMLFormat<T>) xmlFormat;
    }
}

From source file:it.delli.mwebc.utils.DefaultCastHelper.java

public Object toType(String value, Class<?> type) {
    Object obj = null;//  w  ww. j  av a 2  s  .  com
    try {
        if (value != null) {
            if (type.getName().equals(String.class.getName())) {
                obj = toString(value);
            } else if (type.getName().equals(String[].class.getName())) {
                obj = toStringArray(value);
            } else if (type.getName().equals(Character.class.getName())) {
                obj = toCharacter(value);
            } else if (type.getName().equals(Character[].class.getName())) {
                obj = toCharacterArray(value);
            } else if (type.getName().equals(Integer.class.getName())) {
                obj = toInteger(value);
            } else if (type.getName().equals(Integer[].class.getName())) {
                obj = toIntegerArray(value);
            } else if (type.getName().equals(Long.class.getName())) {
                obj = toLong(value);
            } else if (type.getName().equals(Long[].class.getName())) {
                obj = toLongArray(value);
            } else if (type.getName().equals(Double.class.getName())) {
                obj = toDouble(value);
            } else if (type.getName().equals(Double[].class.getName())) {
                obj = toDoubleArray(value);
            } else if (type.getName().equals(Boolean.class.getName())) {
                obj = toBoolean(value);
            } else if (type.getName().equals(Boolean[].class.getName())) {
                obj = toBooleanArray(value);
            } else if (type.getName().equals(Date.class.getName())) {
                obj = toDate(value);
            } else if (type.getName().equals(Date[].class.getName())) {
                obj = toDateArray(value);
            } else if (type.getName().equals(Color.class.getName())) {
                obj = toColor(value);
            } else if (type.getName().equals(Color[].class.getName())) {
                obj = toColorArray(value);
            } else if (type.isEnum()) {
                for (int i = 0; i < type.getEnumConstants().length; i++) {
                    if (type.getEnumConstants()[i].toString().equals(value)) {
                        obj = type.getEnumConstants()[i];
                    }
                }
            } else if (type.isArray() && type.getComponentType().isEnum()) {
                String[] tmp = value.split(",");
                Enum[] array = new Enum[tmp.length];
                for (int j = 0; j < tmp.length; j++) {
                    String item = tmp[j].trim();
                    for (int i = 0; i < type.getComponentType().getEnumConstants().length; i++) {
                        if (type.getComponentType().getEnumConstants()[i].toString().equals(item)) {
                            array[j] = (Enum) type.getComponentType().getEnumConstants()[i];
                        }
                    }
                }
                obj = array;
            } else if (type.getName().equals(Map.class.getName())
                    || type.getName().equals(HashMap.class.getName())
                    || type.getName().equals(LinkedHashMap.class.getName())) {
                obj = toMap(value, type);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return obj;
}

From source file:org.icelib.beans.ObjectMapping.java

@SuppressWarnings({ "unchecked", "restriction", "rawtypes" })
public static <V> V value(Object value, Class<V> targetClass, Object... constructorArgs) {

    Transformer<Object, V> t = (Transformer<Object, V>) objectConverters
            .get(new ClassKey(value.getClass(), targetClass));
    if (t != null) {
        return (V) (t.transform(value));
    }//from   w  ww.j  av a2  s  . co m

    if (value instanceof Number) {
        if (targetClass.equals(Long.class) || targetClass.equals(long.class)) {
            return (V) ((Long) (((Number) value).longValue()));
        } else if (targetClass.equals(Double.class) || targetClass.equals(double.class)) {
            return (V) ((Double) (((Number) value).doubleValue()));
        } else if (targetClass.equals(Integer.class) || targetClass.equals(int.class)) {
            return (V) ((Integer) (((Number) value).intValue()));
        } else if (targetClass.equals(Short.class) || targetClass.equals(short.class)) {
            return (V) ((Short) (((Number) value).shortValue()));
        } else if (targetClass.equals(Float.class) || targetClass.equals(float.class)) {
            return (V) ((Float) (((Number) value).floatValue()));
        } else if (targetClass.equals(Byte.class) || targetClass.equals(byte.class)) {
            return (V) ((Byte) (((Number) value).byteValue()));
        } else if (targetClass.equals(Boolean.class) || targetClass.equals(boolean.class)) {
            return (V) ((Boolean) (((Number) value).intValue() != 0));
        } else if (targetClass.equals(String.class)) {
            return (V) (value.toString());
        } else {
            throw new IllegalArgumentException(
                    String.format("Cannot convert number %s to %s", value, targetClass));
        }
    } else if (value instanceof Boolean) {
        return (V) (((Boolean) value));
    } else if (value instanceof String) {
        if (targetClass.equals(Long.class)) {
            return (V) ((Long) Long.parseLong((String) value));
        } else if (targetClass.equals(Double.class)) {
            return (V) ((Double) Double.parseDouble((String) value));
        } else if (targetClass.equals(Integer.class)) {
            return (V) ((Integer) Integer.parseInt((String) value));
        } else if (targetClass.equals(Short.class)) {
            return (V) ((Short) Short.parseShort((String) value));
        } else if (targetClass.equals(Float.class)) {
            return (V) ((Float) Float.parseFloat((String) value));
        } else if (targetClass.equals(Byte.class)) {
            return (V) ((Byte) Byte.parseByte((String) value));
        } else if (targetClass.equals(Boolean.class)) {
            return (V) ((Boolean) Boolean.parseBoolean((String) value));
        } else if (targetClass.equals(String.class)) {
            return (V) (value.toString());
        } else if (targetClass.isEnum()) {
            for (V ev : targetClass.getEnumConstants()) {
                if (ev.toString().toLowerCase().equalsIgnoreCase(value.toString())) {
                    return ev;
                }
            }
            throw new IllegalArgumentException(String.format("Unknown enum %s in %s", value, targetClass));
        } else {
            // Maybe the target has a constructor that takes a string
            try {
                Constructor<V> con = targetClass.getConstructor(String.class);
                return con.newInstance((String) value);
            } catch (NoSuchMethodException nsme) {
                // That's it, give up
                throw new IllegalArgumentException(
                        String.format("Cannot convert string %s to %s", value, targetClass));
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                throw new RuntimeException(e);
            }

        }
    } else if (value instanceof Map) {
        /*
         * This covers ScriptObjectMirror from Nashorn which is a list AND a
         * map describing an object or an array. It also covers ordinary map
         * and lists
         */

        if (isScriptNativeArray(value)) {
            Collection<?> c = ((jdk.nashorn.api.scripting.ScriptObjectMirror) value).values();
            if (c instanceof List && MappedList.class.isAssignableFrom(targetClass)) {
                try {
                    V v = getTargetInstance(value, targetClass, constructorArgs);
                    for (Object o : ((List) c)) {
                        ((List) v).add(o);
                    }
                    return v;
                } catch (NoSuchMethodException e) {
                    throw new IllegalArgumentException(String.format(
                            "No zero-length constructor for class %s and no valid constructor args provided.",
                            targetClass));
                } catch (InstantiationException | SecurityException | IllegalAccessException
                        | IllegalArgumentException | InvocationTargetException e) {
                    throw new RuntimeException(String.format("Could not construct %s", targetClass), e);
                }
            } else if ((List.class.isAssignableFrom(targetClass) && c instanceof List)
                    || (Collection.class.isAssignableFrom(targetClass) && c instanceof Collection)) {
                return (V) c;
            } else if (Set.class.isAssignableFrom(targetClass)) {
                return (V) new LinkedHashSet<Object>(c);
            } else if (Collection.class.isAssignableFrom(targetClass)) {
                return (V) new ArrayList<Object>(c);
            } else if (targetClass.isArray()) {
                return (V) c.toArray((Object[]) Array.newInstance(targetClass.getComponentType(), c.size()));
            }
        } else if (value instanceof List && List.class.isAssignableFrom(targetClass)) {
            return (V) ((List<?>) value);
        } else if (!isScriptNativeObject(value) && Map.class.isAssignableFrom(targetClass)) {
            return (V) ((Map<?, ?>) value);
        } else {
            try {
                V v = getTargetInstance(value, targetClass, constructorArgs);
                ObjectMapper<?> m = new ObjectMapper<>(v);
                try {
                    m.map((Map<String, Object>) value);
                } catch (Exception e) {
                    throw new RuntimeException(String.format("Failed to map %s.", targetClass), e);
                }
                return v;
            } catch (NoSuchMethodException e) {
                throw new IllegalArgumentException(String.format(
                        "No zero-length constructor for class %s and no valid constructor args provided.",
                        targetClass));
            } catch (InstantiationException | SecurityException | IllegalAccessException
                    | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException(String.format("Could not construct %s", targetClass), e);
            }
        }
    } else if (targetClass.isAssignableFrom(value.getClass())) {
        return (V) value;
    } else if (value instanceof Collection && List.class.isAssignableFrom(targetClass)) {
        try {
            V v = getTargetInstance(value, targetClass, constructorArgs);
            ((List) v).addAll((Collection) value);
            return v;
        } catch (InstantiationException | SecurityException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            throw new RuntimeException(String.format("Could not construct %s", targetClass), e);
        } catch (NoSuchMethodException nse) {
        }
    }
    throw new IllegalArgumentException(
            String.format("Cannot convert %s (%s) to %s", value, value.getClass(), targetClass));
}

From source file:fr.certu.chouette.command.Command.java

private void removeAttribute(Object object, String attrname, String value) throws Exception {
    Class<?> beanClass = object.getClass();
    Method adder = findAdder(beanClass, attrname);
    Class<?> type = adder.getParameterTypes()[0];
    if (type.getName().startsWith("fr.certu.chouette.model.neptune") && !type.getName().startsWith("Enum")) {
        type = Integer.TYPE;/*from  w  ww. j a v  a  2  s  . c o  m*/
    } else {

    }
    Method remover = findRemover(beanClass, attrname, type);
    Object arg = null;
    if (type.isEnum()) {
        arg = toEnum(type, value);
    } else if (type.isPrimitive()) {
        arg = toPrimitive(type, value);
    } else {
        arg = toObject(type, value);
    }
    remover.invoke(object, arg);

}

From source file:fr.certu.chouette.command.Command.java

/**
 * @param object// w  w  w  .j a va2 s.  com
 * @param attrname
 * @param value
 * @throws Exception
 */
private void setAttribute(Object object, String attrname, String value) throws Exception {
    String name = attrname.toLowerCase();
    if (name.equals("id")) {
        throw new Exception("non writable attribute id for any object , process stopped ");
    }
    if (!name.equals("objectid") && !name.equals("creatorid") && !name.equals("areacentroid")
            && name.endsWith("id")) {
        throw new Exception(
                "non writable attribute " + attrname + " use setReference instand , process stopped ");
    }
    Class<?> beanClass = object.getClass();
    Method setter = findSetter(beanClass, attrname);
    Class<?> type = setter.getParameterTypes()[0];
    if (type.isArray() || type.getSimpleName().equals("List")) {
        throw new Exception("list attribute " + attrname + " for object " + beanClass.getName()
                + " must be update with (add/remove)Attribute, process stopped ");
    }
    Object arg = null;
    if (type.isEnum()) {
        arg = toEnum(type, value);
    } else if (type.isPrimitive()) {
        arg = toPrimitive(type, value);
    } else {
        arg = toObject(type, value);
    }
    setter.invoke(object, arg);
}