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:org.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void enumWithNullValue() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/enumWithNullValue.json",
            "com.example");

    Class<Enum> nullEnumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.EnumWithNullValue");

    assertThat(nullEnumClass.isEnum(), is(true));
    assertThat(nullEnumClass.getEnumConstants().length, is(1));

}

From source file:fr.norad.jaxrs.doc.parser.ModelJacksonParser.java

@Override
public List<PropertyAccessor> findProperties(Class<?> modelClass) {
    List<PropertyAccessor> properties = new ArrayList<>();

    BasicBeanDescription beanDesc = fakeSerializer.getDescription(modelClass);
    List<BeanPropertyDefinition> findProperties = beanDesc.findProperties();
    for (BeanPropertyDefinition beanPropertyDefinition : findProperties) {
        if (modelClass.isEnum() && "declaringClass".equals(beanPropertyDefinition.getName())) {
            continue;
        }// ww  w  .  j  ava  2 s .  c om
        AnnotatedMethod getterJackson = beanPropertyDefinition.getGetter();
        AnnotatedMethod setterJackson = beanPropertyDefinition.getSetter();
        AnnotatedField fieldJackson = null;
        try {
            fieldJackson = beanPropertyDefinition.getField();
        } catch (Exception e) {
            log.warning("Name conflict on fields in bean : " + beanPropertyDefinition + " during doc generation"
                    + e.getMessage());
        }

        Method getter = getterJackson == null ? null : getterJackson.getAnnotated();
        Method setter = setterJackson == null ? null : setterJackson.getAnnotated();
        Field field = fieldJackson == null ? null : fieldJackson.getAnnotated();
        if (getter == null && setter == null && field == null) {
            log.warning(
                    "Cannot find valid property element for : " + beanPropertyDefinition + " on " + modelClass);
            continue;
        }

        PropertyAccessor property = new PropertyAccessor();
        property.setField(field);
        property.setGetter(getter);
        property.setSetter(setter);
        property.setName(beanPropertyDefinition.getName());

        properties.add(property);
    }
    return properties;
}

From source file:org.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void enumWithEmptyStringAsValue() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/enumWithEmptyString.json",
            "com.example");

    Class<Enum> emptyEnumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.EnumWithEmptyString");

    assertThat(emptyEnumClass.isEnum(), is(true));
    assertThat(emptyEnumClass.getEnumConstants()[0].name(), is("__EMPTY__"));

}

From source file:com.mstiles92.plugins.stileslib.config.ConfigObject.java

@SuppressWarnings("rawtypes")
protected boolean isEnum(Class clazz, Object obj) {
    if (!clazz.isEnum())
        return false;
    for (Object constant : clazz.getEnumConstants()) {
        if (constant.equals(obj)) {
            return true;
        }//from  w  w  w  .j ava  2 s . c  o  m
    }
    return false;
}

From source file:com.evolveum.midpoint.repo.sql.query2.resolution.ItemPathResolver.java

/**
 * This method provides transformation from {@link String} value defined in
 * {@link com.evolveum.midpoint.repo.sql.query.definition.VirtualQueryParam#value()} to real object. Currently only
 * to simple types and enum values./*  w ww.ja v a2  s. co  m*/
 */
private Object createQueryParamValue(VirtualQueryParam param) throws QueryException {
    Class type = param.type();
    String value = param.value();

    try {
        if (type.isPrimitive()) {
            return type.getMethod("valueOf", new Class[] { String.class }).invoke(null, new Object[] { value });
        }

        if (type.isEnum()) {
            return Enum.valueOf(type, value);
        }
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | RuntimeException ex) {
        throw new QueryException("Couldn't transform virtual query parameter '" + param.name()
                + "' from String to '" + type + "', reason: " + ex.getMessage(), ex);
    }

    throw new QueryException("Couldn't transform virtual query parameter '" + param.name()
            + "' from String to '" + type + "', it's not yet implemented.");
}

From source file:org.apache.sqoop.model.ConfigUtils.java

/**
 * Parse given input JSON string and move it's values to given configuration
 * object./*from ww w  .  j  a  v a 2 s. c  o m*/
 *
 * @param json JSON representation of the configuration object
 * @param configuration ConfigurationGroup object to be filled
 */
@SuppressWarnings("unchecked")
public static void fillValues(String json, Object configuration) {
    Class<?> klass = configuration.getClass();

    Set<String> configNames = new HashSet<String>();
    JSONObject jsonConfigs = (JSONObject) JSONValue.parse(json);

    for (Field configField : klass.getDeclaredFields()) {
        configField.setAccessible(true);
        String configName = configField.getName();

        // We're processing only config validations
        Config configAnnotation = configField.getAnnotation(Config.class);
        if (configAnnotation == null) {
            continue;
        }
        configName = getConfigName(configField, configAnnotation, configNames);

        try {
            configField.set(configuration, configField.getType().newInstance());
        } catch (Exception e) {
            throw new SqoopException(ModelError.MODEL_005, "Issue with field " + configName, e);
        }

        JSONObject jsonInputs = (JSONObject) jsonConfigs.get(configField.getName());
        if (jsonInputs == null) {
            continue;
        }

        Object configValue;
        try {
            configValue = configField.get(configuration);
        } catch (IllegalAccessException e) {
            throw new SqoopException(ModelError.MODEL_005, "Issue with field " + configName, e);
        }

        for (Field inputField : configField.getType().getDeclaredFields()) {
            inputField.setAccessible(true);
            String inputName = inputField.getName();

            Input inputAnnotation = inputField.getAnnotation(Input.class);

            if (inputAnnotation == null || jsonInputs.get(inputName) == null) {
                try {
                    inputField.set(configValue, null);
                } catch (IllegalAccessException e) {
                    throw new SqoopException(ModelError.MODEL_005,
                            "Issue with field " + configName + "." + inputName, e);
                }
                continue;
            }

            Class<?> type = inputField.getType();

            try {
                if (type == String.class) {
                    inputField.set(configValue, jsonInputs.get(inputName));
                } else if (type.isAssignableFrom(Map.class)) {
                    Map<String, String> map = new HashMap<String, String>();
                    JSONObject jsonObject = (JSONObject) jsonInputs.get(inputName);
                    for (Object key : jsonObject.keySet()) {
                        map.put((String) key, (String) jsonObject.get(key));
                    }
                    inputField.set(configValue, map);
                } else if (type == Integer.class) {
                    inputField.set(configValue, ((Long) jsonInputs.get(inputName)).intValue());
                } else if (type.isEnum()) {
                    inputField.set(configValue, Enum.valueOf((Class<? extends Enum>) inputField.getType(),
                            (String) jsonInputs.get(inputName)));
                } else if (type == Boolean.class) {
                    inputField.set(configValue, (Boolean) jsonInputs.get(inputName));
                } else {
                    throw new SqoopException(ModelError.MODEL_004, "Unsupported type " + type.getName()
                            + " for input " + configName + "." + inputName);
                }
            } catch (IllegalAccessException e) {
                throw new SqoopException(ModelError.MODEL_005,
                        "Issue with field " + configName + "." + inputName, e);
            }
        }
    }
}

From source file:org.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void doubleEnumAtRootCreatesIntBackedEnum() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/doubleEnumAsRoot.json",
            "com.example");

    Class<Enum> rootEnumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.enums.DoubleEnumAsRoot");

    assertThat(rootEnumClass.isEnum(), is(true));
    assertThat(rootEnumClass.getDeclaredMethod("fromValue", Double.class), is(notNullValue()));
    assertThat(isPublic(rootEnumClass.getModifiers()), is(true));
}

From source file:java2typescript.jackson.module.StaticFieldExporter.java

private AbstractType typeScriptTypeFromJavaType(Module module, Class<?> type) {
    if (type == boolean.class) {
        return BooleanType.getInstance();
    } else if (type == int.class) {
        return NumberType.getInstance();
    } else if (type == double.class) {
        return NumberType.getInstance();
    } else if (type == String.class) {
        return StringType.getInstance();
    } else if (type.isEnum()) {
        return tsJsonFormatVisitorWrapper.parseEnumOrGetFromCache(module, SimpleType.construct(type));
    } else if (type.isArray()) {
        return new ArrayType(AnyType.getInstance());
    }//from w w  w.  ja v a 2 s.co m
    throw new UnsupportedOperationException();
}

From source file:org.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void intEnumAtRootCreatesIntBackedEnum() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/integerEnumAsRoot.json",
            "com.example");

    Class<Enum> rootEnumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.enums.IntegerEnumAsRoot");

    assertThat(rootEnumClass.isEnum(), is(true));
    assertThat(rootEnumClass.getDeclaredMethod("fromValue", Integer.class), is(notNullValue()));
    assertThat(isPublic(rootEnumClass.getModifiers()), is(true));
}

From source file:io.github.benas.jpopulator.impl.PopulatorImpl.java

protected <T> T populateBeanImpl(final Class<T> type, PopulatorContext context) {
    T result;//  w w w . j  a v  a 2  s  .c o m
    try {

        //No instantiation needed for enum types.
        if (type.isEnum()) {
            return (T) enumRandomizer.<Enum>getRandomEnumValue((Class<Enum>) type);
        }

        if (context.hasPopulatedBean(type)) {
            // The bean already exists in the context, reuse it to avoid recursion.
            return context.getPopulatedBean(type);
        }

        try {
            result = type.newInstance();
        } catch (ReflectiveOperationException ex) {
            Objenesis objenesis = new ObjenesisStd();
            result = objenesis.newInstance(type);
        }

        context.addPopulatedBean(type, result);
        List<Field> declaredFields = getDeclaredFields(result);

        declaredFields.addAll(getInheritedFields(type));

        //Generate random data for each field
        for (Field field : declaredFields) {
            if (shouldExcludeField(field, context) || isStatic(field)) {
                continue;
            }
            populateField(result, field, context);
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, String.format("Unable to populate an instance of type %s", type), e);
        return null;
    }

    return result;
}