Skip to content

Instantly share code, notes, and snippets.

@tlivings
Created November 21, 2010 16:37
Show Gist options
  • Select an option

  • Save tlivings/708882 to your computer and use it in GitHub Desktop.

Select an option

Save tlivings/708882 to your computer and use it in GitHub Desktop.
Simplistic utility class loads scripts into Java interfaces
public class ScriptObjectLoader {
public static ScriptEngineManager scriptEngineManager;
public static ScriptEngine engine;
static {
scriptEngineManager = new ScriptEngineManager();
engine = scriptEngineManager.getEngineByName("JavaScript"); //Or whatever
}
/**
* Loads and wraps a script in an interface.
*
* Usage example:
*
* MyInterface foo = ScriptObjectLoader.<MyInterface>loadScript(MyInterface.class,scriptInputStream);
*
* @param <T> The interface to wrap this script object with
* @param type The interface class
* @param scriptInputStream
* @return
*/
static public <T> T loadScript(Class<? extends T> type, InputStream scriptInputStream) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(scriptInputStream));
return ((Invocable)engine).getInterface(engine.eval(reader), type);
}
catch(ScriptException e) {
//TODO : Handle this appropriately!
e.printStackTrace();
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment