public static Field makeAccessible(Class<?> target, String fieldName) { try { final Field field = target.getDeclaredField(fieldName); return (Field) AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws IllegalAccessException, InvocationTargetException { if (!field.isAccessible()) field.setAccessible(true); return field; } }); } catch (NoSuchFieldException | PrivilegedActionException e) { System.out.print(""); } // keep quiet IError.printStackTrace(e); } return null; }
/** Invoke a method on an object using reflection. */ public static Object invoke(final Object target, final Method method, final Object... args) { try { return AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws IllegalAccessException, InvocationTargetException { if (!method.isAccessible()) method.setAccessible( true); // Say please - else invoke() will fail if method is protected return method.invoke(target, args); } }); } catch (PrivilegedActionException e) { e.printStackTrace(); } return null; }