Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.