Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Field;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> T getFieldValue(Object object, Field field) {
        setAccessibleIfNeeded(field);
        try {
            return (T) field.get(object);
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Object getFieldValue(Object object, String fieldName) {
        try {
            final Field field = getField(object.getClass(), fieldName);
            if (field == null) {
                throw new IllegalArgumentException("No field '" + fieldName + "' found in "
                        + object.getClass().getName() + " or its super classes");
            }
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            return field.get(object);
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void setAccessibleIfNeeded(Field field) {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
    }

    public static Field getField(Class<?> clazz, String fieldName) {
        final Field[] fields = clazz.getDeclaredFields();
        final Field field = getField(fields, fieldName);
        if (field == null) {
            final Class<?> superClass = clazz.getSuperclass();
            if (Object.class.equals(superClass)) {
                return null;
            }
            return getField(superClass, fieldName);
        }
        return field;
    }

    private static Field getField(Field[] fields, String fieldName) {
        for (final Field field : fields) {
            if (fieldName.equals(field.getName())) {
                return field;
            }
        }
        return null;
    }
}