Skip to content

Instantly share code, notes, and snippets.

@ryoasai
Created April 29, 2011 17:06
Show Gist options
  • Save ryoasai/948627 to your computer and use it in GitHub Desktop.
Save ryoasai/948627 to your computer and use it in GitHub Desktop.
You can instantiate an inner class without an enclosing instance.
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();
}
}
@ryoasai
Copy link
Author

ryoasai commented Apr 29, 2011

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment