Skip to content

Instantly share code, notes, and snippets.

@patrickgombert
Created March 4, 2012 23:05
Show Gist options
  • Save patrickgombert/1975268 to your computer and use it in GitHub Desktop.
Save patrickgombert/1975268 to your computer and use it in GitHub Desktop.
Java Hotswapping example
/** 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