001 /* 002 * Created on Jan 1, 2008 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 * 014 * Copyright @2008-2009 the original author or authors. 015 */ 016 package org.fest.reflect.util; 017 018 import java.lang.reflect.AccessibleObject; 019 import java.security.AccessController; 020 import java.security.PrivilegedAction; 021 022 /** 023 * Understands utility methods related to <code>{@link AccessibleObject}</code>s. 024 * 025 * @author Alex Ruiz 026 */ 027 public final class Accessibles { 028 029 /** 030 * Sets the <code>accessible</code> flag of the given <code>{@link AccessibleObject}</code> to the given 031 * <code>boolean</code> value, ignoring any thrown exception. 032 * @param o the given <code>AccessibleObject</code>. 033 * @param accessible the value to set the <code>accessible</code> flag to. 034 */ 035 public static void setAccessibleIgnoringExceptions(AccessibleObject o, boolean accessible) { 036 try { 037 setAccessible(o, accessible); 038 } catch (RuntimeException ignored) {} 039 } 040 041 /** 042 * Sets the <code>accessible</code> flag of the given <code>{@link AccessibleObject}</code> to <code>true</code>. 043 * @param o the given <code>AccessibleObject</code>. 044 * @throws SecurityException if the request is denied. 045 */ 046 public static void makeAccessible(AccessibleObject o) { 047 setAccessible(o, true); 048 } 049 050 /** 051 * Sets the <code>accessible</code> flag of the given <code>{@link AccessibleObject}</code> to the given 052 * <code>boolean</code> value. 053 * @param o the given <code>AccessibleObject</code>. 054 * @param accessible the value to set the <code>accessible</code> flag to. 055 * @throws SecurityException if the request is denied. 056 */ 057 public static void setAccessible(AccessibleObject o, boolean accessible) { 058 AccessController.doPrivileged(new SetAccessibleAction(o, accessible)); 059 } 060 061 private static class SetAccessibleAction implements PrivilegedAction<Void> { 062 private final AccessibleObject o; 063 private final boolean accessible; 064 065 SetAccessibleAction(AccessibleObject o, boolean accessible) { 066 this.o = o; 067 this.accessible = accessible; 068 } 069 070 public Void run() { 071 o.setAccessible(accessible); 072 return null; 073 } 074 } 075 076 private Accessibles() {} 077 }