MethodInvoker implements JavaScriptFunction { @Override public void call(final JsonArray arguments) { try { final Class<?>[] paramTypes = method.getParameterTypes(); final List<Object> paramList = new ArrayList<>(paramTypes.length); for (int i = 0; i < paramTypes.length; ++i) { if (Boolean.class.isAssignableFrom(paramTypes[i])) { paramList.add(arguments.getBoolean(i)); } else if (Double.class.isAssignableFrom(paramTypes[i])) { paramList.add(arguments.getNumber(i)); } else if (String.class.isAssignableFrom(paramTypes[i])) { paramList.add(arguments.getString(i)); } else { paramList.add(arguments.get(i)); } } method.setAccessible(true); method.invoke(object, paramList.toArray()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } MethodInvoker(final Object object, final Method method); @Override void call(final JsonArray arguments);  }
@Test public void testCall() { JreJsonFactory jsonFactory = new JreJsonFactory(); JsonArray params = jsonFactory.createArray(); params.set(0, true); params.set(1, "hey"); params.set(2, 88.0); JsonArray innerArray = jsonFactory.createArray(); innerArray.set(0, "inner"); params.set(3, innerArray); TestTarget target = new TestTarget(); Method testMethod = Arrays .stream(TestTarget.class.getDeclaredMethods()) .filter(m -> "testMethod".equals(m.getName())).findFirst() .get(); MethodInvoker invoker = new MethodInvoker(target, testMethod); invoker.call(params); assertEquals(Boolean.TRUE, target.getArg1()); assertEquals("hey", target.getArg2()); assertEquals(new Double(88.0), target.getArg3()); assertEquals(1, target.getArg4().length()); assertEquals("inner", ((JsonString) target.getArg4().get(0)).getString()); }
@Test(expected = Exception.class) public void testCallInvalidArgs() { JreJsonFactory jsonFactory = new JreJsonFactory(); JsonArray params = jsonFactory.createArray(); params.set(0, true); params.set(1, "hey"); TestTarget target = new TestTarget(); Method testMethod = Arrays .stream(TestTarget.class.getDeclaredMethods()) .filter(m -> "testMethod".equals(m.getName())).findFirst() .get(); MethodInvoker invoker = new MethodInvoker(target, testMethod); invoker.call(params); }
@Test(expected = RuntimeException.class) public void testCallException() { JreJsonFactory jsonFactory = new JreJsonFactory(); JsonArray params = jsonFactory.createArray(); TestTarget target = new TestTarget(); Method testMethod = Arrays .stream(TestTarget.class.getDeclaredMethods()) .filter(m -> "testMethodExc".equals(m.getName())).findFirst() .get(); MethodInvoker invoker = new MethodInvoker(target, testMethod); invoker.call(params); }