Skip to content

Instantly share code, notes, and snippets.

@stuartwdouglas
Created February 19, 2013 09:38
Show Gist options
  • Save stuartwdouglas/4984406 to your computer and use it in GitHub Desktop.
Save stuartwdouglas/4984406 to your computer and use it in GitHub Desktop.
Unicorn by stack trace inspection
public class MagicLand {
public static void main(String[] args) {
for (int i = 0; i < (Math.random() * 500) + 2; i++) {
if (Unicorn.pat()) {
System.out.println("UNICORN #1: PAT THIS UNICORN ONCE");
}
}
for (int i = 0; i < (Math.random() * 500) + 2; i++) {
if (Unicorn.pat()) {
System.out.println("UNICORN #2: PAT THIS UNICORN ONCE");
}
}
System.out.println("END OF PROGRAM");
}
static class Unicorn {
static Integer magicLandLine;
public static boolean pat() {
if (magicLandLine == null) {
StackTraceElement[] trace = new Exception().getStackTrace();
for (StackTraceElement element : trace) {
if (element.getClassName().equals("MagicLand")) {
magicLandLine = element.getLineNumber();
return true;
}
}
} else {
StackTraceElement[] trace = new Exception().getStackTrace();
for (StackTraceElement element : trace) {
if (element.getClassName().equals("MagicLand") && magicLandLine != element.getLineNumber()) {
magicLandLine = element.getLineNumber();
return true;
}
}
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment