Example usage for java.lang Enum valueOf

List of usage examples for java.lang Enum valueOf

Introduction

In this page you can find the example usage for java.lang Enum valueOf.

Prototype

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 

Source Link

Document

Returns the enum constant of the specified enum type with the specified name.

Usage

From source file:io.twipple.springframework.data.clusterpoint.convert.DefaultClusterpointEntityConverter.java

/**
 * Potentially convert simple values like ENUMs.
 *
 * @param value  the value to convert.//from  w ww  . j a va 2  s  .c  om
 * @param target the target object.
 * @return the potentially converted object.
 */
@SuppressWarnings("unchecked")
private Object getPotentiallyConvertedSimpleRead(Object value, Class<?> target) {
    if (value == null || target == null) {
        return value;
    }

    if (conversions.hasCustomReadTarget(value.getClass(), target)) {
        return conversionService.convert(value, target);
    }

    if (Enum.class.isAssignableFrom(target)) {
        return Enum.valueOf((Class<Enum>) target, value.toString());
    }

    if (Class.class.isAssignableFrom(target)) {
        try {
            return Class.forName(value.toString());
        } catch (ClassNotFoundException e) {
            throw new MappingException("Unable to create class from " + value.toString());
        }
    }

    return target.isAssignableFrom(value.getClass()) ? value : conversionService.convert(value, target);
}

From source file:com.kakao.helper.SharedPreferencesCache.java

private void deserializeKey(String key) throws JSONException {
    String jsonString = file.getString(key, "{}");
    JSONObject json = new JSONObject(jsonString);

    String valueType = json.getString(JSON_VALUE_TYPE);

    if (valueType.equals(TYPE_BOOLEAN)) {
        memory.putBoolean(key, json.getBoolean(JSON_VALUE));
    } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        boolean[] array = new boolean[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getBoolean(i);
        }//w  w  w  .  j av a 2  s .  c o m
        memory.putBooleanArray(key, array);
    } else if (valueType.equals(TYPE_BYTE)) {
        memory.putByte(key, (byte) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        byte[] array = new byte[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (byte) jsonArray.getInt(i);
        }
        memory.putByteArray(key, array);
    } else if (valueType.equals(TYPE_SHORT)) {
        memory.putShort(key, (short) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        short[] array = new short[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (short) jsonArray.getInt(i);
        }
        memory.putShortArray(key, array);
    } else if (valueType.equals(TYPE_INTEGER)) {
        memory.putInt(key, json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int[] array = new int[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getInt(i);
        }
        memory.putIntArray(key, array);
    } else if (valueType.equals(TYPE_LONG)) {
        memory.putLong(key, json.getLong(JSON_VALUE));
    } else if (valueType.equals(TYPE_LONG_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        long[] array = new long[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getLong(i);
        }
        memory.putLongArray(key, array);
    } else if (valueType.equals(TYPE_FLOAT)) {
        memory.putFloat(key, (float) json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        float[] array = new float[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (float) jsonArray.getDouble(i);
        }
        memory.putFloatArray(key, array);
    } else if (valueType.equals(TYPE_DOUBLE)) {
        memory.putDouble(key, json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        double[] array = new double[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getDouble(i);
        }
        memory.putDoubleArray(key, array);
    } else if (valueType.equals(TYPE_CHAR)) {
        String charString = json.getString(JSON_VALUE);
        if (charString != null && charString.length() == 1) {
            memory.putChar(key, charString.charAt(0));
        }
    } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        char[] array = new char[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            String charString = jsonArray.getString(i);
            if (charString != null && charString.length() == 1) {
                array[i] = charString.charAt(0);
            }
        }
        memory.putCharArray(key, array);
    } else if (valueType.equals(TYPE_STRING)) {
        memory.putString(key, json.getString(JSON_VALUE));
    } else if (valueType.equals(TYPE_STRING_LIST)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int numStrings = jsonArray.length();
        ArrayList<String> stringList = new ArrayList<String>(numStrings);
        for (int i = 0; i < numStrings; i++) {
            Object jsonStringValue = jsonArray.get(i);
            stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue);
        }
        memory.putStringArrayList(key, stringList);
    } else if (valueType.equals(TYPE_ENUM)) {
        try {
            String enumType = json.getString(JSON_VALUE_ENUM_TYPE);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType);
            @SuppressWarnings("unchecked")
            Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE));
            memory.putSerializable(key, enumValue);
        } catch (ClassNotFoundException e) {
            Logger.getInstance().w(TAG, "Error deserializing key '" + key + "' -- " + e);
        } catch (IllegalArgumentException e) {
            Logger.getInstance().w(TAG, "Error deserializing key '" + key + "' -- " + e);
        }
    }
}

From source file:org.grails.datastore.mapping.engine.NativeEntryEntityPersister.java

protected void refreshObjectStateFromNativeEntry(PersistentEntity persistentEntity, Object obj,
        Serializable nativeKey, T nativeEntry, boolean isEmbedded) {
    EntityAccess ea = createEntityAccess(persistentEntity, obj, nativeEntry);
    ea.setConversionService(getMappingContext().getConversionService());
    if (!(persistentEntity instanceof EmbeddedPersistentEntity)) {

        String idName = ea.getIdentifierName();
        ea.setProperty(idName, nativeKey);
    }//from  w w  w. j  av  a  2  s. c  om

    final List<PersistentProperty> props = persistentEntity.getPersistentProperties();
    for (final PersistentProperty prop : props) {
        String propKey = getNativePropertyKey(prop);
        if (prop instanceof Simple) {
            ea.setProperty(prop.getName(), getEntryValue(nativeEntry, propKey));
        } else if (prop instanceof Basic) {
            Object entryValue = getEntryValue(nativeEntry, propKey);
            if (entryValue instanceof Map) {
                entryValue = new LinkedHashMap((Map) entryValue);
            } else if (entryValue instanceof Collection) {
                Collection collection = MappingUtils.createConcreteCollection(prop.getType());

                Class propertyType = prop.getType();
                Class genericType = MappingUtils.getGenericTypeForProperty(persistentEntity.getJavaClass(),
                        prop.getName());
                Collection collectionValue = (Collection) entryValue;
                if (genericType != null && genericType.isEnum()) {
                    for (Object o : collectionValue) {
                        if (!(o instanceof Enum)) {
                            collection.add(Enum.valueOf(genericType, o.toString()));
                        }
                    }
                } else {
                    collection.addAll(collectionValue);
                }

                entryValue = collection;
            }
            ea.setProperty(prop.getName(), entryValue);
        } else if (prop instanceof Custom) {
            handleCustom(prop, ea, nativeEntry);
        } else if (prop instanceof ToOne) {
            if (prop instanceof Embedded) {
                Embedded embedded = (Embedded) prop;
                T embeddedEntry = getEmbedded(nativeEntry, propKey);

                if (embeddedEntry != null) {
                    Object embeddedInstance = newEntityInstance(embedded.getAssociatedEntity());
                    createEntityAccess(embedded.getAssociatedEntity(), embeddedInstance);
                    refreshObjectStateFromNativeEntry(embedded.getAssociatedEntity(), embeddedInstance, null,
                            embeddedEntry, true);
                    ea.setProperty(propKey, embeddedInstance);
                }
            }

            else {
                ToOne association = (ToOne) prop;

                Serializable tmp = null;
                if (!association.isForeignKeyInChild()) {
                    tmp = (Serializable) getEntryValue(nativeEntry, propKey);
                } else {
                    if (association.isBidirectional()) {

                        Query query = session.createQuery(association.getAssociatedEntity().getJavaClass());
                        query.eq(association.getInverseSide().getName(), obj).projections().id();

                        tmp = (Serializable) query.singleResult();
                    } else {
                        // TODO: handle unidirectional?
                    }

                }
                if (isEmbeddedEntry(tmp)) {
                    PersistentEntity associatedEntity = ((ToOne) prop).getAssociatedEntity();
                    Object instance = newEntityInstance(associatedEntity);
                    refreshObjectStateFromNativeEntry(associatedEntity, instance, null, (T) tmp, false);
                    ea.setProperty(prop.getName(), instance);
                } else if (tmp != null && !prop.getType().isInstance(tmp)) {
                    PersistentEntity associatedEntity = association.getAssociatedEntity();
                    final Serializable associationKey = (Serializable) getMappingContext()
                            .getConversionService().convert(tmp, associatedEntity.getIdentity().getType());
                    if (associationKey != null) {

                        PropertyMapping<Property> associationPropertyMapping = prop.getMapping();
                        boolean isLazy = isLazyAssociation(associationPropertyMapping);

                        final Class propType = prop.getType();
                        if (isLazy) {
                            Object proxy = getProxyFactory().createProxy(session, propType, associationKey);
                            ea.setProperty(prop.getName(), proxy);
                        } else {
                            ea.setProperty(prop.getName(), session.retrieve(propType, associationKey));
                        }
                    }
                }
            }
        } else if (prop instanceof EmbeddedCollection) {
            final Object embeddedInstances = getEntryValue(nativeEntry, propKey);
            loadEmbeddedCollection((EmbeddedCollection) prop, ea, embeddedInstances, propKey);
        } else if (prop instanceof OneToMany) {
            Association association = (Association) prop;
            PropertyMapping<Property> associationPropertyMapping = association.getMapping();

            if (isEmbedded) {
                List keys = loadEmbeddedCollectionKeys((Association) prop, ea, nativeEntry);
                if (List.class.isAssignableFrom(association.getType())) {
                    ea.setPropertyNoConversion(association.getName(), new PersistentList(keys,
                            association.getAssociatedEntity().getJavaClass(), session));
                } else if (Set.class.isAssignableFrom(association.getType())) {
                    ea.setPropertyNoConversion(association.getName(),
                            new PersistentSet(keys, association.getAssociatedEntity().getJavaClass(), session));
                }
            } else {
                boolean isLazy = isLazyAssociation(associationPropertyMapping);
                AssociationIndexer indexer = getAssociationIndexer(nativeEntry, association);
                nativeKey = (Serializable) getMappingContext().getConversionService().convert(nativeKey,
                        getPersistentEntity().getIdentity().getType());
                if (isLazy) {
                    if (List.class.isAssignableFrom(association.getType())) {
                        ea.setPropertyNoConversion(association.getName(),
                                new PersistentList(nativeKey, session, indexer));
                    } else if (SortedSet.class.isAssignableFrom(association.getType())) {
                        ea.setPropertyNoConversion(association.getName(),
                                new PersistentSortedSet(nativeKey, session, indexer));
                    } else if (Set.class.isAssignableFrom(association.getType())) {
                        ea.setPropertyNoConversion(association.getName(),
                                new PersistentSet(nativeKey, session, indexer));
                    }
                } else {
                    if (indexer != null) {
                        List keys = indexer.query(nativeKey);
                        ea.setProperty(association.getName(),
                                session.retrieveAll(association.getAssociatedEntity().getJavaClass(), keys));
                    }
                }
            }
        } else if (prop instanceof ManyToMany) {
            ManyToMany manyToMany = (ManyToMany) prop;
            PropertyMapping<Property> associationPropertyMapping = manyToMany.getMapping();

            boolean isLazy = isLazyAssociation(associationPropertyMapping);
            nativeKey = (Serializable) getMappingContext().getConversionService().convert(nativeKey,
                    getPersistentEntity().getIdentity().getType());
            Class childType = manyToMany.getAssociatedEntity().getJavaClass();
            Collection cached = ((SessionImplementor) session).getCachedCollection(persistentEntity, nativeKey,
                    manyToMany.getName());
            if (cached == null) {
                Collection collection;
                if (isLazy) {
                    Collection keys = getManyToManyKeys(persistentEntity, obj, nativeKey, nativeEntry,
                            manyToMany);
                    if (List.class.isAssignableFrom(manyToMany.getType())) {
                        collection = new PersistentList(keys, childType, session);
                        ea.setPropertyNoConversion(manyToMany.getName(), collection);
                    } else if (Set.class.isAssignableFrom(manyToMany.getType())) {
                        collection = new PersistentSet(keys, childType, session);
                        ea.setPropertyNoConversion(manyToMany.getName(), collection);
                    } else {
                        collection = Collections.emptyList();
                    }
                } else {
                    AssociationIndexer indexer = getAssociationIndexer(nativeEntry, manyToMany);
                    if (indexer == null) {
                        if (List.class.isAssignableFrom(manyToMany.getType())) {
                            collection = Collections.emptyList();
                        } else if (Set.class.isAssignableFrom(manyToMany.getType())) {
                            collection = Collections.emptySet();
                        } else {
                            collection = Collections.emptyList();
                        }
                    } else {
                        List keys = indexer.query(nativeKey);
                        collection = session.retrieveAll(childType, keys);
                        ea.setProperty(manyToMany.getName(), collection);
                    }
                }
                ((SessionImplementor) session).cacheCollection(persistentEntity, nativeKey, collection,
                        manyToMany.getName());
            } else {
                ea.setProperty(manyToMany.getName(), cached);
            }
        }
    }
}

From source file:com.l2jfree.gameserver.model.skills.L2Skill.java

public L2Skill(StatsSet set) {
    _id = L2Integer.valueOf(set.getInteger("skill_id"));
    _level = set.getInteger("level");
    _refId = set.getInteger("referenceId", set.getInteger("itemConsumeId", 0));
    _afroId = set.getInteger("afroId", 0);
    _displayId = set.getInteger("displayId", _id);
    _name = set.getString("name").intern();
    _skillType = set.getEnum("skillType", L2SkillType.class);
    _operateType = set.getEnum("operateType", SkillOpType.class);
    _targetType = set.getEnum("target", SkillTargetType.class);
    _magic = set.getBool("isMagic", isSkillTypeMagic());
    _itemSkill = set.getBool("isItem", 3080 <= getId() && getId() <= 3259);
    _isPotion = set.getBool("isPotion", false);
    _staticReuse = set.getBool("staticReuse", false);
    _staticHitTime = set.getBool("staticHitTime", false);
    _mpConsume = set.getInteger("mpConsume", 0);
    _mpInitialConsume = set.getInteger("mpInitialConsume", 0);
    _hpConsume = set.getInteger("hpConsume", 0);
    _cpConsume = set.getInteger("cpConsume", 0);
    _itemConsume = set.getInteger("itemConsumeCount", 0);
    _itemConsumeId = set.getInteger("itemConsumeId", 0);
    _targetConsume = set.getInteger("targetConsumeCount", 0);
    _targetConsumeId = set.getInteger("targetConsumeId", 0);
    _afterEffectId = set.getInteger("afterEffectId", 0);
    _afterEffectLvl = set.getInteger("afterEffectLvl", 1);

    _isHerbEffect = _name.contains("Herb");

    _castRange = set.getInteger("castRange", 0);
    _effectRange = set.getInteger("effectRange", -1);

    _abnormalLvl = set.getInteger("abnormalLvl", -1);
    _effectAbnormalLvl = set.getInteger("effectAbnormalLvl", -1); // support for a separate effect abnormal lvl, e.g. poison inside a different skill
    _negateLvl = set.getInteger("negateLvl", -1);
    String str = set.getString("negateStats", "");

    if (str == "")
        _negateStats = new L2SkillType[0];
    else {// ww  w  .  ja  v a 2  s  .c  o m
        String[] stats = str.split(" ");
        L2SkillType[] array = new L2SkillType[stats.length];

        for (int i = 0; i < stats.length; i++) {
            L2SkillType type = null;
            try {
                type = Enum.valueOf(L2SkillType.class, stats[i]);
            } catch (Exception e) {
                throw new IllegalArgumentException("SkillId: " + _id + " Enum value of type "
                        + L2SkillType.class.getName() + " required, but found: " + stats[i]);
            }

            array[i] = type;
        }
        _negateStats = array;
    }

    String negateId = set.getString("negateId", null);
    if (negateId != null) {
        String[] valuesSplit = negateId.split(",");
        _negateId = new int[valuesSplit.length];
        for (int i = 0; i < valuesSplit.length; i++) {
            _negateId[i] = Integer.parseInt(valuesSplit[i]);
        }
    } else
        _negateId = new int[0];

    _negatePhysicalOnly = set.getBool("negatePhysicalOnly", false);

    _maxNegatedEffects = set.getInteger("maxNegated", 0);
    _stayAfterDeath = set.getBool("stayAfterDeath", false);
    _killByDOT = set.getBool("killByDOT", false);

    _hitTime = set.getInteger("hitTime", 0);
    _coolTime = set.getInteger("coolTime", 0);
    _skillInterruptTime = set.getInteger("interruptTime", Math.min(_hitTime, 500));
    _reuseDelay = set.getInteger("reuseDelay", 0);
    _equipDelay = set.getInteger("equipDelay", 0);

    _isDance = set.getBool("isDance", false);
    _isSong = set.getBool("isSong", false);
    if (_isDance || _isSong)
        _timeMulti = Config.ALT_DANCE_TIME;
    else if (_skillType == L2SkillType.BUFF) //This should correct the time effect that was caused on debuffs on AltBuffTime config
        _timeMulti = Config.ALT_BUFF_TIME;
    else
        _timeMulti = 1; //If the skills is not a DANCE type skill or BUFF type, the effect time is the normal, without any multiplier

    _skillRadius = set.getInteger("skillRadius", 80);

    _power = set.getFloat("power", 0.f);

    _levelDepend = set.getInteger("lvlDepend", 1);
    _ignoreResists = set.getBool("ignoreResists", false);

    _feed = set.getInteger("feed", 0); // Used for pet food

    _effectType = set.getEnum("effectType", L2SkillType.class, null);
    _effectPower = set.getInteger("effectPower", 0);
    _effectId = set.getInteger("effectId", 0);
    _effectLvl = set.getFloat("effectLevel", 0.f);
    _skill_landing_percent = set.getInteger("skill_landing_percent", 0);
    _element = set.getByte("element", (byte) -1);
    _elementPower = set.getInteger("elementPower", 0);
    _activateRate = set.getInteger("activateRate", -1);
    _magicLevel = initMagicLevel(set);

    _ignoreShld = set.getBool("ignoreShld", false);
    _condition = set.getInteger("condition", 0);
    _overhit = set.getBool("overHit", false);
    _isSuicideAttack = set.getBool("isSuicideAttack", false);
    _weaponsAllowed = set.getInteger("weaponsAllowed", 0);
    _armorsAllowed = set.getInteger("armorsAllowed", 0);

    _needCharges = set.getInteger("needCharges", 0);
    _giveCharges = set.getInteger("giveCharges", 0);
    _maxCharges = set.getInteger("maxCharges", 0);

    _minPledgeClass = set.getInteger("minPledgeClass", 0);

    final ChanceCondition chanceCondition = ChanceCondition.parse(set);
    final TriggeredSkill triggeredSkill = TriggeredSkill.parse(set);

    if (isValid(chanceCondition, triggeredSkill)) {
        _chanceCondition = chanceCondition;
        _triggeredSkill = triggeredSkill;
    } else {
        _chanceCondition = null;
        _triggeredSkill = null;
    }

    _offensiveState = getOffensiveState(set);
    _isDebuff = set.getBool("isDebuff", false/*isOffensive()*/);

    _numSouls = set.getInteger("num_souls", 0);
    _soulConsume = set.getInteger("soulConsumeCount", 0);
    _soulMaxConsume = set.getInteger("soulMaxConsumeCount", 0);
    _expNeeded = set.getInteger("expNeeded", 0);
    _critChance = set.getInteger("critChance", 0);

    // Stats for transformation Skill
    _transformId = set.getInteger("transformId", 0);

    _baseCritRate = set.getInteger("baseCritRate",
            (_skillType == L2SkillType.PDAM || _skillType == L2SkillType.BLOW) ? 0 : -1);
    _lethalEffect1 = set.getInteger("lethal1", 0);
    _lethalEffect2 = set.getInteger("lethal2", 0);
    _directHpDmg = set.getBool("dmgDirectlyToHp", false);
    _nextDanceCost = set.getInteger("nextDanceCost", 0);
    _sSBoost = set.getFloat("SSBoost", 2);

    _aggroPoints = set.getInteger("aggroPoints", 0);

    _flyType = set.getEnum("flyType", FlyType.class, null);
    _flyRadius = set.getInteger("flyRadius", 200);
    _flyCourse = set.getFloat("flyCourse", 0);
    _canBeReflected = set.getBool("canBeReflected", true);
    _canBeDispeled = set.getBool("canBeDispeled", true);
    _dispelOnAction = set.getBool("dispelOnAction", false);
    _dispelOnAttack = set.getBool("dispelOnAttack", false);
    _attribute = set.getString("attribute", "");
    _ignoreShield = set.getBool("ignoreShld", false);
    _sendToClient = set.getBool("sendToClient", true);
    _pvpPowerMulti = set.getFloat("pvpPowerMulti", 1);
}

From source file:com.smartbear.postman.PostmanImporter.java

private void sendAnalytics() {
    Class analyticsClass;//from  w  ww . j  av a2s .  co  m
    try {
        analyticsClass = Class.forName("com.smartbear.analytics.Analytics");
    } catch (ClassNotFoundException e) {
        return;
    }
    try {
        Method getManagerMethod = analyticsClass.getMethod("getAnalyticsManager");
        Object analyticsManager = getManagerMethod.invoke(null);
        Class analyticsCategoryClass = Class.forName("com.smartbear.analytics.AnalyticsManager$Category");
        Method trackMethod = analyticsManager.getClass().getMethod("trackAction", analyticsCategoryClass,
                String.class, Map.class);
        trackMethod.invoke(analyticsManager, Enum.valueOf(analyticsCategoryClass, "CUSTOM_PLUGIN_ACTION"),
                "CreatedProjectBasedOnPostmanCollection", null);
    } catch (Throwable e) {
        logger.error("Error while sending analytics", e);
    }
}

From source file:org.kuali.kra.irb.ProtocolDaoOjb.java

private CritField getCriteriaEnum(Entry<String, String> entry) {

    String searchKeyName = entry.getKey();
    CritField critField = Enum.valueOf(CritField.class, searchMap.get(searchKeyName));
    critField.setFieldValue(entry.getValue());
    return critField;
}

From source file:com.l2jfree.gameserver.templates.StatsSet.java

/**
 * Returns an enumeration of &lt;T&gt; from the set. If the enumeration is empty, the method returns the value of the parameter "deflt".
 * /*from  ww  w . j  a  v a2s.com*/
 * @param <T> : Class of the enumeration returned
 * @param name : String designating the key in the set
 * @param enumClass : Class designating the class of the value associated with the key in the set
 * @param deflt : <T> designating the value by default
 * @return Enum<T>
 */
@SuppressWarnings("unchecked")
public final <T extends Enum<T>> T getEnum(String name, Class<T> enumClass, T deflt) {
    Object val = get(name);
    if (val == null)
        return deflt;
    if (enumClass.isInstance(val))
        return (T) val;
    try {
        return Enum.valueOf(enumClass, String.valueOf(val));
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Enum value of type " + enumClass.getName() + "required, but found: " + val);
    }
}

From source file:com.nestedbird.modules.formparser.FormParse.java

/**
 * Parse enum//from w  ww.j av a 2 s . c o  m
 *
 * @param value value of enum
 * @param type  type of enum
 * @return enum index
 */
@SuppressWarnings("unchecked")
private Object parseEnum(final String value, final Class type) {
    return Enum.valueOf(type, value);
}

From source file:com.kakao.util.helper.SharedPreferencesCache.java

private void deserializeKey(String key) throws JSONException {
    String jsonString = file.getString(key, "{}");
    JSONObject json = new JSONObject(jsonString);

    String valueType = json.getString(JSON_VALUE_TYPE);

    if (valueType.equals(TYPE_BOOLEAN)) {
        memory.putBoolean(key, json.getBoolean(JSON_VALUE));
    } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        boolean[] array = new boolean[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getBoolean(i);
        }/*from   w  ww  .  ja va  2  s  .  co  m*/
        memory.putBooleanArray(key, array);
    } else if (valueType.equals(TYPE_BYTE)) {
        memory.putByte(key, (byte) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        byte[] array = new byte[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (byte) jsonArray.getInt(i);
        }
        memory.putByteArray(key, array);
    } else if (valueType.equals(TYPE_SHORT)) {
        memory.putShort(key, (short) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        short[] array = new short[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (short) jsonArray.getInt(i);
        }
        memory.putShortArray(key, array);
    } else if (valueType.equals(TYPE_INTEGER)) {
        memory.putInt(key, json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int[] array = new int[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getInt(i);
        }
        memory.putIntArray(key, array);
    } else if (valueType.equals(TYPE_LONG)) {
        memory.putLong(key, json.getLong(JSON_VALUE));
    } else if (valueType.equals(TYPE_LONG_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        long[] array = new long[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getLong(i);
        }
        memory.putLongArray(key, array);
    } else if (valueType.equals(TYPE_FLOAT)) {
        memory.putFloat(key, (float) json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        float[] array = new float[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (float) jsonArray.getDouble(i);
        }
        memory.putFloatArray(key, array);
    } else if (valueType.equals(TYPE_DOUBLE)) {
        memory.putDouble(key, json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        double[] array = new double[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getDouble(i);
        }
        memory.putDoubleArray(key, array);
    } else if (valueType.equals(TYPE_CHAR)) {
        String charString = json.getString(JSON_VALUE);
        if (charString != null && charString.length() == 1) {
            memory.putChar(key, charString.charAt(0));
        }
    } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        char[] array = new char[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            String charString = jsonArray.getString(i);
            if (charString != null && charString.length() == 1) {
                array[i] = charString.charAt(0);
            }
        }
        memory.putCharArray(key, array);
    } else if (valueType.equals(TYPE_STRING)) {
        memory.putString(key, json.getString(JSON_VALUE));
    } else if (valueType.equals(TYPE_STRING_LIST)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int numStrings = jsonArray.length();
        ArrayList<String> stringList = new ArrayList<String>(numStrings);
        for (int i = 0; i < numStrings; i++) {
            Object jsonStringValue = jsonArray.get(i);
            stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue);
        }
        memory.putStringArrayList(key, stringList);
    } else if (valueType.equals(TYPE_ENUM)) {
        try {
            String enumType = json.getString(JSON_VALUE_ENUM_TYPE);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType);
            @SuppressWarnings("unchecked")
            Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE));
            memory.putSerializable(key, enumValue);
        } catch (ClassNotFoundException e) {
            Logger.e("SharedPreferences.deserializeKey", "Error deserializing key '" + key + "' -- " + e);
        } catch (IllegalArgumentException e) {
            Logger.e("SharedPreferences.deserializeKey", "Error deserializing key '" + key + "' -- " + e);
        }
    }
}

From source file:net.ceos.project.poi.annotated.core.CellHandler.java

/**
 * Read an enumeration value from the Cell.
 * //from  w  w w .  ja  v a  2s .c o  m
 * @param object
 *            the object
 * @param fT
 *            the class of the field
 * @param field
 *            the {@link Field} to set
 * @param cell
 *            the {@link Cell} to read
 * @throws ConverterException
 *             the conversion exception type
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected static void enumReader(final Object object, final Class<?> fT, final Field field, final Cell cell)
        throws ConverterException {
    if (StringUtils.isNotBlank(cell.getStringCellValue())) {
        try {
            field.set(object, Enum.valueOf((Class<Enum>) fT, cell.getStringCellValue()));
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new ConverterException(ExceptionMessage.CONVERTER_ENUM.getMessage(), e);
        }
    }
}