Java tutorial
//package com.java2s; /** * A collection of small utilities for component management and reflection handling. * <p/> * <hr/> Copyright 2006-2012 Torsten Heup * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ import java.lang.reflect.Field; public class Main { /** * Retrieves the a field with the specified name from the given class. Other than Class's getField(String) method, * this method will also return protected and private fields. * * @param clazz Class from which the field should be obtained. * @param fieldName Name of the field. * @return field with the specified name. */ public static Field getField(final Class clazz, final String fieldName) { try { return clazz.getField(fieldName); } catch (NoSuchFieldException e) { /* Means there's no public field, let's keep looking */ } Class runner = clazz; while (runner != null) { try { return runner.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { /* No luck here either */ } runner = runner.getSuperclass(); } return null; } }