/core/src/main/java/org/fakereplace/reflection/AccessibleObjectReflectionDelegate.java

https://github.com/amkad/fakereplace · Java · 62 lines · 25 code · 7 blank · 30 comment · 3 complexity · a2b1d5f8757ccfe9d122f9c21564ec12 MD5 · raw file

  1. /*
  2. * Copyright 2011, Stuart Douglas
  3. *
  4. * This is free software; you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License as
  6. * published by the Free Software Foundation; either version 2.1 of
  7. * the License, or (at your option) any later version.
  8. *
  9. * This software is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public
  15. * License along with this software; if not, write to the Free
  16. * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  17. * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  18. */
  19. package org.fakereplace.reflection;
  20. import org.fakereplace.com.google.common.collect.MapMaker;
  21. import sun.reflect.Reflection;
  22. import java.lang.reflect.AccessibleObject;
  23. import java.util.Map;
  24. /**
  25. * tracks the accessible state of reflection items
  26. *
  27. * @author stuart
  28. */
  29. public class AccessibleObjectReflectionDelegate {
  30. static Map<AccessibleObject, Boolean> accessibleMap = new MapMaker().weakKeys().makeMap();
  31. public static void setAccessible(AccessibleObject object, boolean accessible) {
  32. accessibleMap.put(object, accessible);
  33. }
  34. public static boolean isAccessible(AccessibleObject object) {
  35. Boolean res = accessibleMap.get(object);
  36. if (res == null) {
  37. return false;
  38. }
  39. return res;
  40. }
  41. /**
  42. * makes sure that a caller has permission to access an AccessibleObject and
  43. * calls setAccessible
  44. *
  45. * @param object
  46. * @param callerStackDepth
  47. */
  48. public static void ensureAccess(AccessibleObject object, int callerStackDepth, Class<?> declaringClass, int modifiers) throws IllegalAccessException {
  49. if (!isAccessible(object)) {
  50. Class<?> caller = sun.reflect.Reflection.getCallerClass(callerStackDepth);
  51. Reflection.ensureMemberAccess(caller, declaringClass, object, modifiers);
  52. }
  53. object.setAccessible(true);
  54. }
  55. }