简体   繁体   中英

Two declared constructors in inner class

I have a public class with a private class inside it:

public class A {

   private class B
   {
   }

   private final B b = new B();

   public static void main(String[] args) {
       Class<?> bClass = A.class.getDeclaredClasses()[0];
       Constructor<?>[] declaredConstructors = bClass.getDeclaredConstructors();
       System.out.println(declaredConstructors.length);  //result = 2
   }
}

The problem is, that the declared constructors in class B equals two.

Although in other cases, the number of constructors in class B equals one:

public class A {

   private class B
   {
       public B()
       {
       }
   }

   private final B b = new B();

   public static void main(String[] args) {
       Class<?> bClass = A.class.getDeclaredClasses()[0];
       Constructor<?>[] declaredConstructors = bClass.getDeclaredConstructors();
       System.out.println(declaredConstructors.length);  //result = 1
   }
}

and

public class A {

   private class B
   {
   }

   public static void main(String[] args) {
       Class<?> bClass = A.class.getDeclaredClasses()[0];
       Constructor<?>[] declaredConstructors = bClass.getDeclaredConstructors();
       System.out.println(declaredConstructors.length);  //result = 1
   }
}

The question is why in the first case 2 constructors? Thanks!

As already shortly mentioned by chrylis what you are seeing here is a synthetic constructor.

Basically, whenever you access private attributes of a nested class from the nesting class the compiler needs to create a synthetic method for this access.

In your first example the default constructor is private so when you call it a synthetic method is created (thus "2" constructors exist).

In your second example the constructor is declared as public and no such issue exists.

In your third example once again it is private but also never accessed so there is no need to create a synthetic method.

If you are interested in more detail, read into Chapter 13.1.7 of the Java Language Specification ( https://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html ) where it is explained a bit further.

Also if you are interested in the implications of synthetic method this post might be interesting to you, discussing the implications of them in regards to security (and performance): What's the penalty for Synthetic methods?

Also, if you want to read more into the inner workings of this concept, I can recommend the following article: https://www.javaworld.com/article/2073578/java-s-synthetic-methods.html (which (to my knowledge) should still be up to date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM