public static Class<?> parseClass(String source, String packageAndClassName) { if (LOADER == null) { throw new RuntimeException( "Compile fail: no Groovy jar in the classpath", INIT_FAIL_EXCEPTION); } try { Object codeSource = Utils.newInstance("groovy.lang.GroovyCodeSource", source, packageAndClassName + ".groovy", "UTF-8"); Utils.callMethod(codeSource, "setCachable", false); Class<?> clazz = (Class<?>) Utils.callMethod( LOADER, "parseClass", codeSource); return clazz; } catch (Exception e) { throw new RuntimeException(e); } } }
/** * Calls a static method via reflection. This will try to use the method * where the most parameter classes match exactly (this algorithm is simpler * than the one in the Java specification, but works well for most cases). * * @param classAndMethod a string with the entire class and method name, eg. * "java.lang.System.gc" * @param params the method parameters * @return the return value from this call */ public static Object callStaticMethod(String classAndMethod, Object... params) throws Exception { int lastDot = classAndMethod.lastIndexOf('.'); String className = classAndMethod.substring(0, lastDot); String methodName = classAndMethod.substring(lastDot + 1); return callMethod(null, Class.forName(className), methodName, params); }
private static Object callMethod( Object instance, Class<?> clazz, String methodName, Object... params) throws Exception { Method best = null; int bestMatch = 0; boolean isStatic = instance == null; for (Method m : clazz.getMethods()) { if (Modifier.isStatic(m.getModifiers()) == isStatic && m.getName().equals(methodName)) { int p = match(m.getParameterTypes(), params); if (p > bestMatch) { bestMatch = p; best = m; } } } if (best == null) { throw new NoSuchMethodException(methodName); } return best.invoke(instance, params); }