Here you can find the source of setField(Field f, Object this_, Object value)
Parameter | Description |
---|---|
AssertionError | if field is final |
public static void setField(Field f, Object this_, Object value)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Field; public class Main { /**//from ww w. j a va2 s . c om * Sets field with specified value in spite of access permission. * * @throws AssertionError if field is final */ public static void setField(Field f, Object this_, Object value) { try { f.setAccessible(true); f.set(this_, value); } catch (IllegalAccessException e) { throw new AssertionError(e); } } /** * Sets field with specified value in spite of access permission. * * @throws AssertionError if no such field in the class or field is final */ public static void setField(Class<?> clazz, String fname, Object this_, Object value, boolean isSearchSuperclass) { try { Field f = findField(clazz, fname, isSearchSuperclass); setField(f, this_, value); } catch (NoSuchFieldException e) { throw new AssertionError(e); } } private static Field findField(Class<?> clazz, String fname, boolean isSearchSuperclass) throws NoSuchFieldException, AssertionError { Field f = null; try { f = clazz.getDeclaredField(fname); } catch (NoSuchFieldException e) { } if (f == null && isSearchSuperclass) { do { clazz = clazz.getSuperclass(); if (clazz == null) { throw new NoSuchFieldException("Class " + clazz + " has no such field: %s" + fname); //$NON-NLS-1$ //$NON-NLS-2$ } try { f = clazz.getDeclaredField(fname); } catch (NoSuchFieldException e) { } } while (f == null); } return f; } public static Object getDeclaredField(String name, Object this_) { try { Field field = this_.getClass().getDeclaredField(name); field.setAccessible(true); return getField(field, this_); } catch (SecurityException e) { throw new AssertionError(e); } catch (NoSuchFieldException e) { throw new AssertionError(e); } } /** * Gets value of field in spite of access permission. */ public static Object getField(Field f, Object this_) { try { f.setAccessible(true); return f.get(this_); } catch (IllegalAccessException e) { throw new AssertionError(e); } } /** * Gets value of field in spite of access permission. * * @throws AssertionError if no such field in the class */ public static Object getField(Class<?> clazz, String fname, Object this_, boolean isSearchSuperclass) { try { Field f = findField(clazz, fname, isSearchSuperclass); return getField(f, this_); } catch (NoSuchFieldException e) { throw new AssertionError(e); } } }