通过指定字段名称来获取对象的字段,它搜索所有声明的字段,但不是静态字段或最终字段,包括私有受保护字段和公共字段
//package com.nowjava; import java.lang.reflect.Field; /* 时 代 J a v a - nowjava.com 提 供 */ 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)// 来自 时 代 J a v a 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())) {