1 18 package org.apache.tools.ant.util; 19 20 import java.lang.reflect.InvocationTargetException ; 21 import java.lang.reflect.Method ; 22 import org.apache.tools.ant.BuildException; 23 import java.lang.reflect.Field ; 24 25 31 32 public class ReflectUtil { 33 34 35 private ReflectUtil() { 36 } 37 38 44 public static Object invoke(Object obj, String methodName) { 45 try { 46 Method method; 47 method = obj.getClass().getMethod( 48 methodName, (Class []) null); 49 return method.invoke(obj, (Object []) null); 50 } catch (Exception t) { 51 throwBuildException(t); 52 return null; } 54 } 55 56 64 public static Object invoke( 65 Object obj, String methodName, Class argType, Object arg) { 66 try { 67 Method method; 68 method = obj.getClass().getMethod( 69 methodName, new Class [] {argType}); 70 return method.invoke(obj, new Object [] {arg}); 71 } catch (Exception t) { 72 throwBuildException(t); 73 return null; } 75 } 76 77 87 public static Object invoke( 88 Object obj, String methodName, Class argType1, Object arg1, 89 Class argType2, Object arg2) { 90 try { 91 Method method; 92 method = obj.getClass().getMethod( 93 methodName, new Class [] {argType1, argType2}); 94 return method.invoke(obj, new Object [] {arg1, arg2}); 95 } catch (Exception t) { 96 throwBuildException(t); 97 return null; } 99 } 100 101 108 public static Object getField(Object obj, String fieldName) 109 throws BuildException { 110 try { 111 Field field = obj.getClass().getDeclaredField(fieldName); 112 field.setAccessible(true); 113 return field.get(obj); 114 } catch (Exception t) { 115 throwBuildException(t); 116 return null; } 118 } 119 120 126 public static void throwBuildException(Exception t) 127 throws BuildException { 128 if (t instanceof InvocationTargetException ) { 129 Throwable t2 = ((InvocationTargetException ) t) 130 .getTargetException(); 131 if (t2 instanceof BuildException) { 132 throw (BuildException) t2; 133 } 134 throw new BuildException(t2); 135 } else { 136 throw new BuildException(t); 137 } 138 } 139 } 140 | Popular Tags |