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

Java examples for Reflection:Field Get

Description

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

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        Object obj = "java2s.com";
        String name = "java2s.com";
        System.out.println(getNoStaticNorFinalField(obj, name));
    }/*ww  w . java 2  s . c o m*/

    /**
     * Get field form an object by appointing field name, it search form all declared fields but not static or final
     * including private protected and public fields
     * @param obj the object to fetch field
     * @param name field name
     * @return destination
     * @throws NoSuchFieldException
     */
    public static Field getNoStaticNorFinalField(Object obj, String name)
            throws NoSuchFieldException {
        return getNoStaticNorFinalField(obj.getClass(), name);
    }

    public static Field getNoStaticNorFinalField(Class<?> c, String name)
            throws NoSuchFieldException {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (!Modifier.isStatic(field.getModifiers())
                    && !Modifier.isFinal(field.getModifiers())) {
                if (field.getName().equals(name)) {
                    return field;
                }
            }
        }
        throw new NoSuchFieldException(String.format("No such field: %s",
                name));
    }
}

Related Tutorials