Java Field from Class getField(Class type, String name)

Here you can find the source of getField(Class type, String name)

Description

returns field for given name in given type

License

Open Source License

Parameter

Parameter Description
type - type of primitive
name - name of field

Return

- field

Declaration

public static Field getField(Class type, String name) 

Method Source Code

//package com.java2s;
/* ===========================================================================
 * $RCS$//from  ww w .  j a va  2  s.  com
 * Version: $Id: ReflectHelper.java,v 2.6 2006/08/18 01:59:13 shahzad Exp $
 * ===========================================================================
 *
 * TestPlayer - an automated test harness builder
 *
 * Copyright (c) 2005-2006 Shahzad Bhatti (bhatti@plexobject.com)
 *
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * The author may be contacted at bhatti@plexobject.com 
 * See http://testplayer.dev.java.net/ for more details.
 *
 */

import java.lang.reflect.*;

public class Main {
    /**
     * returns field for given name in given type
     * @param type - type of primitive
     * @param name - name of field
     * @return - field
     */
    public static Field getField(Class type, String name) {
        try {
            Field result = type.getDeclaredField(name);
            result.setAccessible(true);
            return result;
        } catch (NoSuchFieldException e) {
            throw new IllegalArgumentException("Could not access " + type.getName() + "." + name + " field");
        }
    }
}

Related

  1. findDeclaredField(Class javaClass, String fieldName)
  2. getDeclaredField(final Class javaClass, final String fieldName, final boolean shouldSetAccessible)
  3. getDeclaredFields(final Class clazz)
  4. getField(final Class javaClass, final String fieldName, final boolean shouldSetAccessible)
  5. getJsonValueFieldName(String className)
  6. getProperField(Class objectClass)
  7. setPrivateField(String fieldName, Class containingClass, Object target, Object value)