ClassUtil { public static Object applyMethod(Object pObject, String pMethod, Object ... pArgs) { Class<?> clazz = pObject.getClass(); try { Method method = extractMethod(pMethod, clazz, pArgs); return method.invoke(pObject,pArgs); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Cannot call method " + pMethod + " on " + pObject + ": " + e,e); } catch (InvocationTargetException e) { throw new IllegalArgumentException("Cannot call method " + pMethod + " on " + pObject + ": " + e,e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Cannot call method " + pMethod + " on " + pObject + ": " + e,e); } } private  ClassUtil(); static Class<T> classForName(String pClassName, ClassLoader ... pClassLoaders); static Class<T> classForName(String pClassName,boolean pInitialize,ClassLoader ... pClassLoaders); static InputStream getResourceAsStream(String pPath); static boolean checkForClass(String pClassName); static T newInstance(String pClassName, Object ... pArguments); static T newInstance(Class<T> pClass, Object ... pArguments); static Object applyMethod(Object pObject, String pMethod, Object ... pArgs); static Set<String> getResources(String pResource);  }
@Test public void testApply() { File testFile = new File("/cannot/possibly/exist/at/all"); Boolean result = (Boolean) ClassUtil.applyMethod(testFile,"exists"); assertFalse(result); }
@Test public void testApplyWithPrimitive() { ClassUtilTest test = new ClassUtilTest("bla",1); assertEquals(test.intProp,1); ClassUtil.applyMethod(test,"setIntProp",new Integer(2)); assertEquals(test.intProp,2); }
@Test public void testApplyNoArgs() { String fs = System.getProperty("path.separator"); String pathname = fs + "tmp"; File testFile = new File(pathname); String path = (String) ClassUtil.applyMethod(testFile,"getPath"); assertEquals(path, pathname); }
@Test public void testApplyWithArgs() { Map<String,String> map = new HashMap<String,String>(); ClassUtil.applyMethod(map,"put","hello","world"); assertEquals(map.get("hello"),"world"); }
@Test public void testApplyWithNullArg() { ClassUtilTest test = new ClassUtilTest("set",0); assertEquals(test.stringProp,"set"); ClassUtil.applyMethod(test,"setStringProp",new Object[] { null }); assertEquals(test.stringProp,null); }
@Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*NoSuchMethod.*") public void testApplyWithArgsFail1() { Map<String,String> map = new HashMap<String,String>(); ClassUtil.applyMethod(map, "putBlubber", "hello", "world"); }
@Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*NoSuchMethod.*") public void testApplyWithFail2() { ClassUtilTest test = new ClassUtilTest(); ClassUtil.applyMethod(test,"setStringProp",Boolean.TRUE); }
@Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*NoSuchMethodException.*") public void testApplyFail1() { ClassUtil.applyMethod(new Object(),"bullablu"); }