Created
April 29, 2011 17:06
-
-
Save ryoasai/948627 to your computer and use it in GitHub Desktop.
You can instantiate an inner class without an enclosing instance.
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
import java.lang.reflect.*; | |
public class Outer { | |
private String outer = "outer"; | |
public class Inner { | |
public void hello() { | |
System.out.println("Hello World" + outer); // NullPointerException at this line. | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
Constructor<Inner> c = Inner.class.getConstructor(Outer.class); | |
Inner instance = c.newInstance((Object) null); // Shouldn't be allowed ? | |
instance.hello(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can never instantiate an inner class without an enclosing instance using the usual new operator. But if you use reflection API you can somehow instantiate an inner class without an enclosing instance.
Constructor class's Java doc says:
"If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance; see The Java Language Specification, section 15.9.3."
, so this behavior seems to be a bug.