What is the access type of an anonymous inner class?

I was thinking about classes, and specifically about anonymous inner classes. This made me wonder what the type of access of an anonymous inner class is.

I understand that in most cases this will not change anything, but it can be relevant for reflection, for example. I saw several questions asking about problems using reflection to access the contents of anonymous inner classes.

I found this question (one example of this problem): access exception when calling an anonymous class method using java reflection

And this answer, which assumes that it is private, but the writer could not confirm: https://stackoverflow.com/a/464829/

+6
source share
2 answers

They seem to be publicly available, but the JDK implementation of Method.invoke has a (long-term) error. See error 4071957 .

The related error does not actually correspond to our situation, however, it unites all types of Method.invoke access control problems over inner classes and was noted as a duplicate of error 4819108 , which was related in the accepted answer to the SO question that you mentioned.

+4
source

The class itself has an outer class package.

getModifiers() A value of 8 , which according to the comments: static, package private .

Its static (why?). I cannot reference Main.this from within an anonymous class in Main .

Its package private . However, the access level of an anonymous class does not even mean much, because you cannot use its type at compile time, like a regular class.

https://ideone.com/vzbdQ5

 // JDK 8 import java.lang.reflect.Modifier; public class Main { public static void main(String[] args) throws Exception { Class anon = new Main() {}.getClass(); System.out.println("Name:" + anon.getName()); // Main$1 System.out.println("Anonymous:" + anon.isAnonymousClass()); // true System.out.println("Package:" + anon.getPackage()); // null System.out.println("public ? " + Modifier.isPublic(anon.getModifiers())); // false System.out.println("private ? " + Modifier.isPrivate(anon.getModifiers())); // false System.out.println("protected ? " + Modifier.isProtected(anon.getModifiers())); // false assert anon.newInstance() instanceof Main; assert Class.forName(anon.getName()).newInstance() instanceof Main; } } 
+3
source

All Articles