Java – T::class.java.newInstance() is deprecated

T::class.java.newInstance() is deprecated… here is a solution to the problem.

T::class.java.newInstance() is deprecated

inline fun <reified T> blah(block: T.() -> Unit): Something {
    request = T::class.java.newInstance()

newInstance() has been deprecated, usually when you look at the source code it explains why it is deprecated and what the alternative is, but this time I only see :

/** @deprecated */
@CallerSensitive
@Deprecated(
    since = "9"
)
public T newInstance() throws InstantiationException, IllegalAccessException {
    // ...
}

What is the new way to create instances of materialized types in Kotlin?

Update: More information available upon request:

JDK Version: 11 (not Android, just pure JVM)
Kotlin Version:1.3.61 

Solution

Actually this comes from Java itself. The appropriate replacement is:

T::class.java.getDeclaredConstructor().newInstance()

You can also check Class.newInstance()-JavadocThis also illustrates this.

Related Problems and Solutions