Java Reflection Field Set setFieldVisible( Class classToModify, String fieldName)

Here you can find the source of setFieldVisible( Class classToModify, String fieldName)

Description

Modify the visibility of a field.

License

Open Source License

Parameter

Parameter Description
classToModify The class to modify.
fieldName The name of the field to modify

Exception

Parameter Description
SecurityException In case of problem
NoSuchFieldException In case of problem

Return

The modified field

Declaration

public static Field setFieldVisible(
        Class<? extends Object> classToModify, String fieldName)
        throws SecurityException, NoSuchFieldException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011, 2012 THALES GLOBAL SERVICES.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from w  ww .  ja  va2 s  .  com*/
 *    Obeo - initial API and implementation
 *******************************************************************************/

import java.lang.reflect.Field;

public class Main {
    /**
     * Modify the visibility of a field.
     * 
     * @param classToModify
     *            The class to modify.
     * @param fieldName
     *            The name of the field to modify
     * @return The modified field
     * @throws SecurityException
     *             In case of problem
     * @throws NoSuchFieldException
     *             In case of problem
     */
    public static Field setFieldVisible(
            Class<? extends Object> classToModify, String fieldName)
            throws SecurityException, NoSuchFieldException {
        Field field = null;
        try {
            field = classToModify.getDeclaredField(fieldName);
            field.setAccessible(true);
        } catch (SecurityException e) {
            // DO nothing
        } catch (NoSuchFieldException e) {
            if (classToModify.getSuperclass() != null) {
                field = setFieldVisible(classToModify.getSuperclass(),
                        fieldName);
            }
        }
        return field;
    }
}

Related

  1. setFields(final Map fields, final Object target)
  2. setFieldStatic(final Object pBean, final String fieldname, final Object pInject)
  3. setFieldVal(Object object, String name, Object val)
  4. setFieldValeByType(Field field, Object obj, String value)
  5. setFieldViaReflection(String fieldName, V value, T classInstance)
  6. setFieldWithReflection(Object object, String fieldName, Object fieldValue)