1 package net.sf.uitags.testutil; 2 3 import java.lang.reflect.Field ; 4 import java.lang.reflect.InvocationTargetException ; 5 import java.lang.reflect.Method ; 6 7 30 public final class PrivilegedAccessor { 31 34 private PrivilegedAccessor() { 35 } 37 38 47 public static Object getValue(Object instance, String fieldName) 48 throws IllegalAccessException , NoSuchFieldException { 49 Field field = getField(instance.getClass(), fieldName); 50 field.setAccessible(true); 51 return field.get(instance); 52 } 53 54 66 public static Object invokeMethod( 67 Object instance, String methodName, Object arg) 68 throws NoSuchMethodException , 69 IllegalAccessException , 70 InvocationTargetException { 71 Object [] args = new Object [1]; 72 args[0] = arg; 73 return invokeMethod(instance, methodName, args); 74 } 75 76 88 public static Object invokeMethod( 89 Object instance, String methodName, Object [] args) 90 throws NoSuchMethodException , 91 IllegalAccessException , 92 InvocationTargetException { 93 Class [] classTypes = null; 94 if (args != null) { 95 classTypes = new Class [args.length]; 96 for (int i = 0; i < args.length; i++) { 97 if (args[i] != null) { 98 classTypes[i] = args[i].getClass(); 99 } 100 } 101 } 102 return getMethod(instance,methodName, 103 classTypes).invoke(instance, args); 104 } 105 106 111 public static Method getMethod(Object instance, String methodName, 112 Class [] classTypes) throws NoSuchMethodException { 113 Method accessMethod = getMethod( 114 instance.getClass(), methodName, classTypes); 115 accessMethod.setAccessible(true); 116 return accessMethod; 117 } 118 119 122 private static Field getField(Class thisClass, String fieldName) throws NoSuchFieldException { 123 if (thisClass == null) 124 throw new NoSuchFieldException ("Invalid field : " + fieldName); 125 try { 126 return thisClass.getDeclaredField( fieldName ); 127 } 128 catch(NoSuchFieldException e) { 129 return getField(thisClass.getSuperclass(), fieldName); 130 } 131 } 132 133 137 private static Method getMethod(Class thisClass, String methodName, Class [] classTypes) throws NoSuchMethodException { 138 if (thisClass == null) 139 throw new NoSuchMethodException ("Invalid method : " + methodName); 140 try { 141 return thisClass.getDeclaredMethod( methodName, classTypes ); 142 } 143 catch(NoSuchMethodException e) { 144 return getMethod(thisClass.getSuperclass(), methodName, classTypes); 145 } 146 } 147 } | Popular Tags |