Created
March 4, 2012 23:05
-
-
Save patrickgombert/1975268 to your computer and use it in GitHub Desktop.
Java Hotswapping example
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
/** Message.java **/ | |
public interface Message { | |
public void sayIt(); | |
} | |
/** HelloWorld.java **/ | |
public class HelloWorld implements Message { | |
public void sayIt() { | |
System.out.println("Hello World"); | |
} | |
} | |
/** HelloHotswap.java **/ | |
public class HelloHotswap implements Message { | |
public void sayIt() { | |
System.out.println("Hello Hotswap"); | |
} | |
} | |
/** Main.java **/ | |
public class main { | |
public static void main(String[] args) { | |
String basepath = args[0]; | |
Example example = new Example(basepath); | |
String line = ""; | |
while(true) { | |
try { | |
java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); | |
line = stdin.readLine(); | |
} | |
catch (java.io.IOException e) { System.out.println(e); } | |
catch (NumberFormatException e) { System.out.println(e); } | |
if(line.equals("speak")) { | |
example.speak(); | |
} else if(line.equals("exit")) { | |
System.exit(0); | |
} else { | |
example.changeImpl(line); | |
} | |
} | |
} | |
} | |
/** Example.java **/ | |
import org.codemonkey.javareflection.ExternalClassLoader; | |
public class Example { | |
Class impl; | |
ExternalClassLoader loader; | |
public Example(String basepath) { | |
loader = new ExternalClassLoader(); | |
loader.setBasepath(basepath); | |
} | |
public void changeImpl(String path) { | |
try { | |
impl = loader.loadClass(path); | |
} catch(ClassNotFoundException e) { | |
System.err.println("Class not found"); | |
} catch(Exception e) { | |
System.err.println("Something went wrong"); | |
} | |
} | |
public void speak() { | |
try { | |
Message instance = (Message)impl.newInstance(); | |
instance.sayIt(); | |
} catch(Exception e) { | |
System.err.println("Reflection error"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment