Example usage for java.lang.reflect Field isEnumConstant

List of usage examples for java.lang.reflect Field isEnumConstant

Introduction

In this page you can find the example usage for java.lang.reflect Field isEnumConstant.

Prototype

public boolean isEnumConstant() 

Source Link

Document

Returns true if this field represents an element of an enumerated type; returns false otherwise.

Usage

From source file:Spy.java

public static void main(String... args) throws Exception {
    Class<?> c = Class.forName("Spy");
    Field[] flds = c.getDeclaredFields();
    for (Field f : flds) {
        System.out.println(f.isEnumConstant());

    }//from   w  ww  .  j  a v  a  2 s .co m
}

From source file:EnumSpy.java

public static void main(String... args) {
    try {//from  w ww  .  ja  v  a2s. c  o  m
        Class<?> c = Class.forName(args[0]);
        if (!c.isEnum()) {
            out.format("%s is not an enum type%n", c);
            return;
        }
        out.format("Class:  %s%n", c);

        Field[] flds = c.getDeclaredFields();
        List<Field> cst = new ArrayList<Field>(); // enum constants
        List<Field> mbr = new ArrayList<Field>(); // member fields
        for (Field f : flds) {
            if (f.isEnumConstant())
                cst.add(f);
            else
                mbr.add(f);
        }
        if (!cst.isEmpty())
            print(cst, "Constant");
        if (!mbr.isEmpty())
            print(mbr, "Field");

        Constructor[] ctors = c.getDeclaredConstructors();
        for (Constructor ctor : ctors) {
            out.format(fmt, "Constructor", ctor.toGenericString(), synthetic(ctor));
        }

        Method[] mths = c.getDeclaredMethods();
        for (Method m : mths) {
            out.format(fmt, "Method", m.toGenericString(), synthetic(m));
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:Spy.java

public static void main(String... args) {
    try {/*w w w  . j ava 2s. c o  m*/
        Class<?> c = Class.forName(args[0]);
        int searchMods = 0x0;
        for (int i = 1; i < args.length; i++) {
            searchMods |= modifierFromString(args[i]);
        }

        Field[] flds = c.getDeclaredFields();
        out.format("Fields in Class '%s' containing modifiers:  %s%n", c.getName(),
                Modifier.toString(searchMods));
        boolean found = false;
        for (Field f : flds) {
            int foundMods = f.getModifiers();
            // Require all of the requested modifiers to be present
            if ((foundMods & searchMods) == searchMods) {
                out.format("%-8s [ synthetic=%-5b enum_constant=%-5b ]%n", f.getName(), f.isSynthetic(),
                        f.isEnumConstant());
                found = true;
            }
        }

        if (!found) {
            out.format("No matching fields%n");
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:com.ejisto.modules.web.util.FieldSerializationUtil.java

private static MockedField translateField(Field field, Object container, String className, String contextPath) {
    Class<?> fieldType = field.getType();
    MockedField out = buildMockedField(className, field.getName(), contextPath, fieldType.getName());
    Object value = safeGet(field, container);
    if (value == null || isBlackListed(fieldType)) {
        out.setFieldValue(null);/*from w  ww . j a  v a  2s .  c  o m*/
        return out;
    }
    int hashCode = System.identityHashCode(value);
    String existingClassMapping = CACHED_IDS.putIfAbsent(hashCode, out.getFieldType());
    if (StringUtils.isNotBlank(existingClassMapping)) {
        out.setLink(String.valueOf(hashCode));
        return out;
    } else if (field.isEnumConstant() || fieldType.isPrimitive()) {
        out.setFieldValue(String.valueOf(value));
    } else {
        out.setExpression(translateValue(value));
    }
    out.setRecordedObjectHashCode(hashCode);
    return out;
}

From source file:net.erdfelt.android.sdkfido.configer.EnumConverter.java

public EnumConverter(Class<?> type) {
    this.enumclass = type;
    this.values = new HashMap<String, Object>();

    for (Field f : enumclass.getFields()) {
        if (f.isEnumConstant()) {
            String key = f.getName().toUpperCase();
            try {
                Object val = f.get(null);
                values.put(key, val);
            } catch (IllegalArgumentException e) {
                LOG.log(Level.WARNING, "Unable to get value for field " + type.getName() + "#" + f.getName(),
                        e);//from w w w .j av a 2 s  .c o  m
            } catch (IllegalAccessException e) {
                LOG.log(Level.WARNING, "Unable to get value for field " + type.getName() + "#" + f.getName(),
                        e);
            }
        }
    }
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Builds the enum dict./*from   www.j a  v  a  2 s.c  o  m*/
 *
 * @param <E> the element type
 * @param c   the c
 * @return the map
 */
private static <E extends Enum<E>> Map<String, ExchangeVersion> buildEnumDict(Class<E> c) {
    Map<String, ExchangeVersion> dict = new HashMap<String, ExchangeVersion>();
    Field[] fields = c.getDeclaredFields();
    for (Field f : fields) {
        if (f.isEnumConstant() && f.isAnnotationPresent(RequiredServerVersion.class)) {
            RequiredServerVersion ewsEnum = f.getAnnotation(RequiredServerVersion.class);
            String fieldName = f.getName();
            ExchangeVersion exchangeVersion = ewsEnum.version();
            dict.put(fieldName, exchangeVersion);
        }
    }
    return dict;
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Builds the enum to schema mapping dictionary.
 *
 * @param c class type//from  w w w.j  a  v a2 s  .  c om
 * @return The mapping from enum to schema name
 */
private static Map<String, String> buildEnumToSchemaDict(Class<?> c) {
    Map<String, String> dict = new HashMap<String, String>();
    Field[] fields = c.getFields();
    for (Field f : fields) {
        if (f.isEnumConstant() && f.isAnnotationPresent(EwsEnum.class)) {
            EwsEnum ewsEnum = f.getAnnotation(EwsEnum.class);
            String fieldName = f.getName();
            String schemaName = ewsEnum.schemaName();
            if (!schemaName.isEmpty()) {
                dict.put(fieldName, schemaName);
            }
        }
    }
    return dict;
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Builds the schema to enum mapping dictionary.
 *
 * @param <E> Type of the enum.//from w  w w  . jav a 2  s  . c o  m
 * @param c   Class
 * @return The mapping from enum to schema name
 */
private static <E extends Enum<E>> Map<String, String> buildSchemaToEnumDict(Class<E> c) {
    Map<String, String> dict = new HashMap<String, String>();

    Field[] fields = c.getDeclaredFields();
    for (Field f : fields) {
        if (f.isEnumConstant() && f.isAnnotationPresent(EwsEnum.class)) {
            EwsEnum ewsEnum = f.getAnnotation(EwsEnum.class);
            String fieldName = f.getName();
            String schemaName = ewsEnum.schemaName();
            if (!schemaName.isEmpty()) {
                dict.put(schemaName, fieldName);
            }
        }
    }
    return dict;
}

From source file:net.erdfelt.android.sdkfido.configer.ConfigCmdLineParser.java

private void usage(Configurable cfgr, int maxOptSize) {
    out.print(StringUtils.rightPad(toOptionExample(cfgr), maxOptSize, ' '));

    out.printf(" : %s%n", cfgr.getDescription());
    String indent = StringUtils.rightPad("", maxOptSize + 3);

    if (cfgr.getField() == null) {
        // Manually Added Configurable.
        if (OPT_CONFIG.equals(cfgr.getKey())) {
            out.printf("%s(default value: %s)%n", indent, configer.getPersistFile().getAbsolutePath());
        }/*w  ww . ja v a  2s  .  c  o  m*/
        out.flush();
        return;
    }

    if (cfgr.getField().getType().isEnum()) {
        for (Field f : cfgr.getField().getType().getDeclaredFields()) {
            if (f.isEnumConstant()) {
                out.printf("%s\"%s\"", indent, f.getName());
                ConfigOption copt = f.getAnnotation(ConfigOption.class);
                if (copt != null) {
                    out.printf(" - %s", copt.description());
                }
                out.println();
            }
        }
    }

    Object obj = configer.getValue(cfgr.getName());
    if (obj != null) {
        out.printf("%s(default value: %s)%n", indent, obj);
    }
    out.flush();
}

From source file:io.siddhi.doc.gen.core.utils.DocumentationUtils.java

/**
 * Generate a file from a template//from www  . j  a va 2 s.c o m
 *
 * @param templateFile    The template file name
 * @param dataModel       The data model to be used for generating the output files from template files
 * @param outputDirectory The output directory in which the file will be generated
 * @param outputFileName  The name of the file that will be generated
 * @throws MojoFailureException if the Mojo fails to find template file or create new documentation file
 */
private static void generateFileFromTemplate(String templateFile, Map<String, Object> dataModel,
        String outputDirectory, String outputFileName) throws MojoFailureException {
    // Creating the free marker configuration
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setClassForTemplateLoading(DocumentationUtils.class, File.separator + Constants.TEMPLATES_DIRECTORY);

    // Adding the constants to the freemarker data model
    Map<String, String> constantsClassFieldMap = new HashMap<>();
    for (Field field : Constants.class.getDeclaredFields()) {
        try {
            constantsClassFieldMap.put(field.getName(), field.get(null).toString());
        } catch (IllegalAccessException ignored) { // Ignoring inaccessible variables
        }
    }
    dataModel.put("CONSTANTS", constantsClassFieldMap);

    // Adding the ExtensionType enum values to the freemarker data model
    Map<String, String> extensionTypeEnumMap = new HashMap<>();
    for (Field field : ExtensionType.class.getDeclaredFields()) {
        try {
            if (field.isEnumConstant()) {
                extensionTypeEnumMap.put(field.getName(), ((ExtensionType) field.get(null)).getValue());
            }
        } catch (IllegalAccessException ignored) { // Ignoring inaccessible variables
        }
    }
    dataModel.put("EXTENSION_TYPE", extensionTypeEnumMap);

    try {
        // Fetching the template
        Template template = cfg.getTemplate(templateFile);

        // Generating empty documentation files
        File outputFile = new File(outputDirectory + File.separator + outputFileName);
        if (!outputFile.getParentFile().exists()) {
            if (!outputFile.getParentFile().mkdirs()) {
                throw new MojoFailureException("Unable to create directory " + outputFile.getParentFile());
            }
        }
        if (!outputFile.exists()) {
            if (!outputFile.createNewFile()) {
                throw new MojoFailureException("Unable to create file " + outputFile.getAbsolutePath());
            }
        }

        // Writing to the documentation file
        try (OutputStream outputStream = new FileOutputStream(outputFile)) {
            try (Writer writer = new OutputStreamWriter(outputStream, Charset.defaultCharset())) {
                template.process(dataModel, writer);
            }
        } catch (TemplateException e) {
            throw new MojoFailureException("Invalid Free Marker template found in " + templateFile, e);
        }
    } catch (IOException e) {
        throw new MojoFailureException("Unable to find template file " + templateFile, e);
    }
}