Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getDeclaredConstructors() lists 2 constructors but there is only one

Given this little pice of code:

import java.util.Arrays;

public class Sample {
    private final int test;

    private Sample(int test) {
        this.test = test;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(Hello.class.getDeclaredConstructors()));
    }

    public static class Hello {
        private final int i;

        private Hello(int i) {
            this.i = i;
        }

        public int getI() {
            return i;
        }

        public static class Builder {
            private int i;

            private Builder() {

            }

            public static Builder builder() {
                return new Builder();
            }

            public void add(int i) {
                this.i = i;
            }

            public Hello build() {
                return new Hello(i);
            }
        }
    }
}

i don't understand the output that is shown:

[private Sample$Hello(int), Sample$Hello(int,Sample$1)]

what is the second listed constructor in here with the second parameter to the Builder. I thought that the output will only show the private constructor of Hello but not the second one.

like image 787
BigMichi1 Avatar asked Oct 02 '22 08:10

BigMichi1


1 Answers

Builder is a static nested class of Hello, therefore it should be able to access private constructor Sample$Hello(int).

However, JVM doesn't have any special support for nested classes, therefore, from the JVM point of view, Builder cannot access Sample$Hello(int).

In order to solve this problem compiler generates synthetic constructor Sample$Hello(int,Sample$1) with default visibility, and calls it instead of Sample$Hello(int) from Builder.

Sample$1 is an empty class generated by the compiler to make distinguished signature for Sample$Hello(int,Sample$1). Actually, the second argument of this constructor is always null.

like image 128
axtavt Avatar answered Oct 12 '22 21:10

axtavt