Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

public class Main {
    public static final int TYPE_OBJECT = 0;
    public static final int TYPE_INT = 1;
    public static final int TYPE_SHORT = 2;
    public static final int TYPE_BYTE = 3;
    public static final int TYPE_BOOLEAN = 4;
    public static final int TYPE_FLOAT = 5;
    public static final int TYPE_LONG = 6;
    public static final int TYPE_DOUBLE = 7;

    public static Object getStaticField(Class clz, String fieldName, int type) {
        if (null != clz) {
            try {
                Field field = clz.getField(fieldName);
                switch (type) {
                case TYPE_OBJECT:
                    return field.get(clz);
                case TYPE_INT:
                    return field.getInt(clz);
                case TYPE_SHORT:
                    return field.getShort(clz);
                case TYPE_BYTE:
                    return field.getByte(clz);
                case TYPE_BOOLEAN:
                    return field.getBoolean(clz);
                case TYPE_FLOAT:
                    return field.getFloat(clz);
                case TYPE_LONG:
                    return field.getLong(clz);
                case TYPE_DOUBLE:
                    return field.getDouble(clz);
                default:
                    return field.get(clz);
                }
            } catch (Exception e) {
            }
            return (clz == Object.class ? getDefault(type) : getStaticField(clz.getSuperclass(), fieldName, type));
        }
        return getDefault(type);
    }

    /**
     * @param clz class name
     * @param fieldName field name
     * @return the Field object if the class is exists, else null
     */
    public static Field getField(Class clz, String fieldName) {
        if (null != clz) {
            try {
                return clz.getField(fieldName);
            } catch (Exception e) {
            }
            return (clz == Object.class ? null : getField(clz.getSuperclass(), fieldName));
        }
        return null;
    }

    private static Object getDefault(int type) {
        switch (type) {
        case TYPE_OBJECT:
            return "";
        case TYPE_INT:
        case TYPE_SHORT:
        case TYPE_BYTE:
        case TYPE_BOOLEAN:
        case TYPE_FLOAT:
        case TYPE_LONG:
        case TYPE_DOUBLE:
            return 0;
        default:
            return "";
        }
    }
}