Created
November 21, 2010 16:37
-
-
Save tlivings/708882 to your computer and use it in GitHub Desktop.
Simplistic utility class loads scripts into Java interfaces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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