Skip to content

Instantly share code, notes, and snippets.

@benjholla
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjholla/a05a26eff4d23295199d to your computer and use it in GitHub Desktop.
Save benjholla/a05a26eff4d23295199d to your computer and use it in GitHub Desktop.
Using static and instance initializers to invoke a private method on an anonymous inner class
/**
* Playing around with inner classes and control flow
* @author Ben Holland
*/
public class ExampleClass {
// static initializer
static {
// anonymous inner class
new ExampleClass() {
// instance initializer
@SuppressWarnings("unused")
String benign = doEvil();
// otherwise pointless method?
private String doEvil(){
System.out.println("DOING EVIL...");
return null; // hear no evil, see no evil ;)
}
};
}
/**
* Prints the following to stdout
* <pre><code>DOING EVIL...
* BEHAVING MYSELF...
* </code></pre>
*
* There should be no way to call the doEvil method
* from the main method, except maybe through some fancy
* reflection magic
*
* @param args
*/
public static void main(String[] args){
System.out.println("BEHAVING MYSELF...");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment