Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import java.util.HashMap;

import java.util.Map;

public class Main {
    /**
     * Stores the classes 'static final' field values as a map.
     * 
     * @param clazz
     *            The class containing static field values.
     * @return A map keyed by static field name to value.
     */
    public static Map<String, Object> constantsAsMap(Class<?> clazz) {
        try {
            final Map<String, Object> constants = new HashMap<String, Object>();
            final int staticFinalMods = Modifier.STATIC | Modifier.FINAL;
            for (Field field : clazz.getFields()) {
                if (staticFinalMods == (field.getModifiers() & staticFinalMods)) {
                    // this is a constant!
                    constants.put(field.getName(), field.get(null));
                }
            }

            return constants;
        } catch (Exception e) {
            // wrap in general error
            throw new IllegalStateException("Unable to initialize class constants for: " + clazz);
        }
    }
}