Prevent empty constructors from @Immutable annotations

I use groovy and love @ Optional annotation . The problem is that this annotation not only creates constructors with the specified class fields, but also creates an empty constructor and allows the fields to remain at zero (or accept the default value). I want to prevent this.

Example:

@Immutable class User { int age}

can be called as

User jasmin = new User(30)
println "I am ${jasmin.age} years old" // I am 30 years old

but also like

User james = new User() //Uhoh, I have no age
println "I am ${james.age} years old" // I am 0 years old - maybe not expected

My question is this: are there any annotations or other ways to prevent calling an empty constructor? Probably throws an exception, if not age, the past (or zero passed to it) at run time. Bonus points if I get eclipse IDE support so that during compilation eclipse complains about calling the constructor.

- @NotNull groovy, java , . ? ? - IDE, ?

+4
1

; @Immutable , .

, , , , , . mutable super type , @Immutable. :

import groovy.transform.*

class MutableUser {
    int age
    // defining an explicit constructor suppresses implicit no-args constructor
    MutableUser(int age) { 
        this.age = age 
    }
}

@Immutable
@InheritConstructors
class User extends MutableUser {
}

User jasmin = new User() // results in java.lang.NoSuchMethodError

no-arg.

+2

All Articles