Here you can find the source of findField(final Class> aClass, final String fieldName)
Parameter | Description |
---|---|
aClass | The class to search for the field |
fieldName | the field to search for |
public static Object findField(final Class<?> aClass, final String fieldName)
//package com.java2s; /**//from w ww . j a v a 2 s .c o m * TestHelper.java * Copyright 2005 (c) Andrew Wilson <nuance@sourceforge.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Current Version: $Revision$ * */ import java.lang.reflect.Field; import java.util.Arrays; public class Main { /** * Get the field related to a name * @param aClass The class to search for the field * @param fieldName the field to search for * @return the field related to a name in the class */ public static Object findField(final Class<?> aClass, final String fieldName) { try { Class<?> clazz = aClass; while (true) { for (final Field f : Arrays.asList(clazz .getDeclaredFields())) { if (f.getName().equals(fieldName)) { f.setAccessible(true); return f; } } if (!"Object".equals(clazz.getName())) { clazz = clazz.getSuperclass(); } else { break; } } } catch (SecurityException e) { System.out.println(e); } return null; } }