1 24 25 package org.objectweb.cjdbc.scenario.tools.util; 26 27 import java.lang.reflect.Field ; 28 import java.lang.reflect.InvocationTargetException ; 29 import java.lang.reflect.Method ; 30 31 51 public class PrivilegedAccessor 52 { 53 62 public static Object getValue(Object instance, String fieldName) 63 throws IllegalAccessException , NoSuchFieldException 64 { 65 Field field = getField(instance.getClass(), fieldName); 66 field.setAccessible(true); 67 return field.get(instance); 68 } 69 70 82 public static Object invokeMethod( 83 Object instance, 84 String methodName, 85 Object arg) 86 throws NoSuchMethodException , IllegalAccessException , InvocationTargetException 87 { 88 Object [] args = new Object [1]; 89 args[0] = arg; 90 return invokeMethod(instance, methodName, args); 91 } 92 93 105 public static Object invokeMethod( 106 Object instance, 107 String methodName, 108 Object [] args) 109 throws NoSuchMethodException , IllegalAccessException , InvocationTargetException 110 { 111 Class [] classTypes = null; 112 if (args != null) 113 { 114 classTypes = new Class [args.length]; 115 for (int i = 0; i < args.length; i++) 116 { 117 if (args[i] != null) 118 classTypes[i] = args[i].getClass(); 119 } 120 } 121 return getMethod(instance, methodName, classTypes).invoke(instance, args); 122 } 123 124 131 public static Method getMethod( 132 Object instance, 133 String methodName, 134 Class [] classTypes) 135 throws NoSuchMethodException 136 { 137 Method accessMethod = 138 getMethod(instance.getClass(), methodName, classTypes); 139 accessMethod.setAccessible(true); 140 return accessMethod; 141 } 142 143 151 private static Field getField(Class thisClass, String fieldName) 152 throws NoSuchFieldException 153 { 154 if (thisClass == null) 155 throw new NoSuchFieldException ("Invalid field : " + fieldName); 156 try 157 { 158 return thisClass.getDeclaredField(fieldName); 159 } 160 catch (NoSuchFieldException e) 161 { 162 return getField(thisClass.getSuperclass(), fieldName); 163 } 164 } 165 166 176 private static Method getMethod( 177 Class thisClass, 178 String methodName, 179 Class [] classTypes) 180 throws NoSuchMethodException 181 { 182 if (thisClass == null) 183 throw new NoSuchMethodException ("Invalid method : " + methodName); 184 try 185 { 186 return thisClass.getDeclaredMethod(methodName, classTypes); 187 } 188 catch (NoSuchMethodException e) 189 { 190 return getMethod(thisClass.getSuperclass(), methodName, classTypes); 191 } 192 } 193 } 194 | Popular Tags |