Skip to content

Commit 8d435e6

Browse files
committed
JVM: Don't use deprecated Class#newInstance()
1 parent c43142c commit 8d435e6

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

jvm/src/main/scala/org/portablescala/reflect/InstantiatableClass.scala

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,35 @@
11
package org.portablescala.reflect
22

3-
/** A wrapper for a class that can be instantiated.
3+
import java.lang.reflect.InvocationTargetException
4+
5+
/**
6+
* A wrapper for a class that can be instantiated.
47
*
58
* @param runtimeClass
69
* The `java.lang.Class[_]` representing the class.
710
*/
811
final class InstantiatableClass private[reflect] (val runtimeClass: Class[_]) {
12+
913
/** A list of the public constructors declared in this class. */
1014
val declaredConstructors: List[InvokableConstructor] =
11-
runtimeClass.getConstructors().map(new InvokableConstructor(_)).toList
15+
runtimeClass.getConstructors.map(new InvokableConstructor(_)).toList
1216

13-
/** Instantiates this class using its zero-argument constructor.
17+
/**
18+
* Instantiates this class using its zero-argument constructor.
1419
*
1520
* @throws java.lang.InstantiationException
1621
* (caused by a `NoSuchMethodException`)
1722
* If this class does not have a public zero-argument constructor.
1823
*/
1924
def newInstance(): Any = {
2025
try {
21-
runtimeClass.newInstance()
26+
runtimeClass.getDeclaredConstructor().newInstance()
2227
} catch {
23-
case e: IllegalAccessException =>
28+
case e: InvocationTargetException if e.getCause != null =>
29+
throw e.getCause
30+
case e: NoSuchMethodException =>
31+
throw new InstantiationException(runtimeClass.getName).initCause(e)
32+
case _: IllegalAccessException =>
2433
/* The constructor exists but is private; make it look like it does not
2534
* exist at all.
2635
*/

0 commit comments

Comments
 (0)