Java Reflection Field Find findField(String string, Class clazz)

Here you can find the source of findField(String string, Class clazz)

Description

find Field

License

Apache License

Declaration

public static Field findField(String string, Class<? extends Object> clazz) 

Method Source Code

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

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static Field findField(String string, Object instance)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Class<? extends Object> clazz = instance.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(string)) {
                field.setAccessible(true);
                return field;
            }//  www .  j  a  va  2s  . co  m
        }
        return null;
    }

    public static Field findField(String string, Class<? extends Object> clazz) {
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(string)) {
                field.setAccessible(true);
                return field;
            }
        }
        return null;
    }

    public static List<Field> getDeclaredFields(Class<?> type) {
        Field[] declaredFields = type.getDeclaredFields();
        List<Field> fields = new ArrayList<Field>();
        for (Field field : declaredFields) {
            if (!Modifier.isStatic(field.getModifiers())) {
                fields.add(field);
            }
        }
        return fields;
    }
}

Related

  1. findField(String fieldName, ArrayList fields)
  2. findField(String fieldName, Class cl)
  3. findField(String fieldName, Class type)
  4. findField(String name, Class c)
  5. findField(String name, Object o)
  6. findField0(Class clazz, String name, String methodName)
  7. findFieldByName(Class owner, String name)
  8. findFieldEx(Class type, Class annotationClass)
  9. findFieldFromClassHierarchy(Class clazz, String fieldName)