Last active
August 29, 2015 14:14
-
-
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
This file contains 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
/** | |
* 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