001/* [{ 002Copyright 2010 Nicolas Carranza <nicarran at gmail.com> 003 004This file is part of jpen. 005 006jpen is free software: you can redistribute it and/or modify 007it under the terms of the GNU Lesser General Public License as published by 008the Free Software Foundation, either version 3 of the License, 009or (at your option) any later version. 010 011jpen is distributed in the hope that it will be useful, 012but WITHOUT ANY WARRANTY; without even the implied warranty of 013MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 014GNU Lesser General Public License for more details. 015 016You should have received a copy of the GNU Lesser General Public License 017along with jpen. If not, see <http://www.gnu.org/licenses/>. 018}] */ 019package jpen.internal; 020 021import java.lang.reflect.Field; 022import java.security.AccessController; 023import java.security.PrivilegedActionException; 024import java.security.PrivilegedExceptionAction; 025 026public final class AccessibleField{ 027 private final Class clazz; 028 private final String fieldName; 029 private Field field; 030 031 public AccessibleField(Class clazz, String fieldName){ 032 this.clazz=clazz; 033 this.fieldName=fieldName; 034 } 035 036 public Field getField(){ 037 if(field==null) 038 try{ 039 field=getAccessibleField(clazz, fieldName); 040 }catch(PrivilegedActionException ex){ 041 throw new AssertionError(ex); 042 } 043 return field; 044 } 045 046 private static Field getAccessibleField(final Class clazz, final String fieldName) 047 throws PrivilegedActionException{ 048 return AccessController.doPrivileged(new PrivilegedExceptionAction<Field>(){ 049 //@Override 050 public Field run() throws Exception{ 051 Field field=clazz.getDeclaredField(fieldName); 052 field.setAccessible(true); 053 return field; 054 } 055 }); 056 } 057}