通过指定字段名称来获取对象的字段,它搜索所有声明的字段,但不是静态字段或最终字段,包括私有受保护字段和公共字段
/* from nowjava.com - 时 代 Java*/ //package com.nowjava; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Main { public static void main(String[] argv) throws Exception { Object obj = "nowjava.com"; String name = "nowjava.com"; System.out.println(getNoStaticNorFinalField(obj, name)); } /** * 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)//时代Java公众号 - nowjava.com 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())) {