Get no static field nor final field form an object by appointing field name, it search form all declared fields including private protected and public field - Java Reflection

Java examples for Reflection:Field Get

Description

Get no static field nor final field form an object by appointing field name, it search form all declared fields including private protected and public field

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        Object obj = "java2s.com";
        System.out.println(java.util.Arrays
                .toString(getNoStaticNorFinalFieldArray(obj)));
    }//from  w ww .  j  a va 2s  .co  m

    /**
     * Get no static field nor final field form an object by appointing field name, it search form all declared fields
     * including private protected and public field
     * @param obj the object to fetch fields
     * @return Field array
     */
    public static Field[] getNoStaticNorFinalFieldArray(Object obj) {
        return getNoStaticNorFinalFieldArray(obj.getClass());
    }

    public static Field[] getNoStaticNorFinalFieldArray(Class<?> c) {
        return getNoStaticNorFinalFieldList(c).toArray(new Field[] {});
    }

    /**
     * Get no static field nor final field form an object by appointing field name, it search form all declared fields
     * including private protected and public fields
     * @param obj the object to fetch field
     * @return Field list
     */
    public static List<Field> getNoStaticNorFinalFieldList(Object obj) {
        return getNoStaticNorFinalFieldList(obj.getClass());
    }

    public static List<Field> getNoStaticNorFinalFieldList(Class<?> c) {
        Field[] fields = c.getDeclaredFields();
        List<Field> nostaticFieldList = new ArrayList<Field>();
        for (Field field : fields) {
            field.setAccessible(true);
            if (!Modifier.isStatic(field.getModifiers())
                    && !Modifier.isFinal(field.getModifiers())) {
                nostaticFieldList.add(field);
            }
        }
        return nostaticFieldList;
    }
}

Related Tutorials