Get all fields and return a map via reflection - Java Reflection

Java examples for Reflection:Field Get

Description

Get all fields and return a map via reflection

Demo Code


//package com.java2s;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        System.out.println(getFieldMap(clazz));
    }/*from ww w. j  av a 2s  .c o m*/

    /**
     * Must be non-transient.
     * Must be non-final.
     * Will be set accessible if possible.
     */
    public static Map<String, Field> getFieldMap(Class<?> clazz) {
        Map<String, Field> ret = new HashMap<String, Field>();

        for (Field field : findAllFields(clazz)) {
            if (Modifier.isTransient(field.getModifiers()))
                continue;
            if (Modifier.isFinal(field.getModifiers()))
                continue;
            makeAccessible(field);
            ret.put(field.getName(), field);
        }

        return ret;
    }

    public static List<Field> findAllFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<Field>();
        for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
            fields.addAll(Arrays.asList(c.getDeclaredFields()));
        }
        return fields;
    }

    public static void makeAccessible(Field field) {
        if ((!Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass()
                        .getModifiers()) || Modifier.isFinal(field
                .getModifiers())) && !field.isAccessible()) {
            field.setAccessible(true);
        }
    }

    public static void makeAccessible(Method method) {
        if ((!Modifier.isPublic(method.getModifiers()) || !Modifier
                .isPublic(method.getDeclaringClass().getModifiers()))
                && !method.isAccessible()) {
            method.setAccessible(true);
        }
    }
}

Related Tutorials