jeudi 9 novembre 2017

Scala/java reflection `newInstance` throws InstantiationException

object classof extends App {

 trait Config {
    def test(): Unit
  }

  case class Test() extends Config {
    override def test(): Unit = println("test")
  }

  val s = classOf[Test]

  s.newInstance().test()

}

The above code works fine, but when you run it as a scala worksheet, it throws InstantiationException.

Caused by: java.lang.NoSuchMethodException: 
reflection.A$A20$A$A20$Test.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.newInstance(Class.java:412)

I am facing this issue primarily when executing tests. For example

Animal.config.newInstance().test where Animal is an instantiated object and config holds val config: Class[_ <: Config] = classOf[Test]

I dont have sound knowledge on java reflections.





Aucun commentaire:

Enregistrer un commentaire