Overriding multiple Java constructors with default


#1

Hi All

I need to do the following:

class MyApplicationContext: AnnotationConfigApplicationContext {
    constructor(): super() // This must be default
    constructor(beanFactory: DefaultListableBeanFactory): super(beanFactory)
    constructor(annotatedClass: Class<*>): super(annotatedClass)
    constructor(vararg basePackages: String): super(*basePackages)
}

but with this code I get a runtime exception like:

org.springframework.beans.BeanInstantiationException: Failed to instantiate 
[org.my.app.MyApplicationContext]: No default constructor found; nested exception is java.lang.NoSuchMethodException

	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:127)
	at org.springframework.boot.SpringApplication.createApplicationContext(SpringApplication.java:598)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:324)

Kotlin v 1.2.71
Is there a way to have all overrided Java constructors together with the primary constructor?
Thanks.


#2

This is why this exeption is raised (Spring)

    Constructor<T> ctor = KotlinDetector.isKotlinType(clazz) ? BeanUtils.KotlinDelegate.getPrimaryConstructor(clazz) : clazz.getDeclaredConstructor();

    public static boolean isKotlinType(Class<?> clazz) {
        return kotlinMetadata != null && clazz.getDeclaredAnnotation(kotlinMetadata) != null;
    }

#3

no, there isn’t.

If you have a primary constructor, secondary constructors need to call it.
If you don’t have a primary constructor, the secondary constructor may call each other or call super.

you have an @JvmOverloads, which adds java-constructor with a couple of constructors, but this is very limited (gives only a couple of constructors).
In this case that doesn’t really help,but in future cases it might…