Ordiel
Ordiel

Reputation: 2633

Differentiate provided default no args constructor from declared one

Simple question: How can I differentiate a default constructor. i.e:

class AClass { } // will have a default no args constructor -> public AClass() {}

from one specified like:

class AClass {
    private final int i;

    public AClass() { i = 0; }
}

Checking the options reflection libraries provide I am not able to find any that allows me to distinguish one from another...

I've tried mostly with the methods provided by Class#get*Constructor(s)

Maybe I got tunnel vision, and I am forgetting something or there is another approach to this I am missing... any help would be appreciated!

EDIT:

This is the method I'm using, there is where I need to detect if such constructor is user defined or not:

    protected void adaptAfterLoading(final Class<?> loadedClass) {
        Arrays.asList(loadedClass.getDeclaredConstructors()).forEach(System.out::println);
        System.out.println("$$$$$$$$$$$ " + loadedClass.getDeclaredConstructors());
        Arrays
                .stream(loadedClass.getDeclaredConstructors())
                .filter(
                        ((Predicate<Constructor<?>>) Constructor::isSynthetic)
                                .negate())
                .map(ConstructorRep::loadFrom)
                .forEach(this::addConstructor);
    }

So... in case you were wondering why isSynthetic does not work:

From here:

13.1. The Form of a Binary - 7. Any constructs introduced by a Java compiler that do not have a corresponding construct in the source code must be marked as synthetic, except for default constructors, the class initialization method, and the values and valueOf methods of the Enum class.

Upvotes: 1

Views: 52

Answers (1)

Dorian Gray
Dorian Gray

Reputation: 2981

There is simply no way to detect that, as there is no difference in the compiled bytecode.

A class with default constructor

class AClass { } // will have a default no args constructor 

is implicitely compiled as

class AClass { 
    AClass() {}
}

The first form is merely syntactic sugar.

Also your next example

class AClass {
    private final int i;

    public AClass() { i = 0; }
}

Could be written with a default constructor in an equivalent form

class AClass {
    private final int i = 0;
}

Beside, I fail to see a use case where you would have to detect that.

Upvotes: 1

Related Questions