I am trying to change a compiler plugin some other person wrote which runs directly after the typer and I want to generate code that throws an Exception.
The Exception class looks like this:
case class MyException(message: String) extends Exception(message)
In the actual code, this is an inner class, though.
I looked how he got the symbols of a fixed class and did it similarly, I don't know if there is a better way but here is how he did it:
val exceptionClass = MyException.getClass.getName
val exceptionName = if (exceptionClass.last == '$') exceptionClass.dropRight(1) else exceptionClass
val symbol = rootMirror.getModuleByName(newTermName(exceptionName))
To throw the exception, I did this:
import CODE._
THROW(symbol, Literal(Constant("My message")))
I think, the following are also equivalent (and yield equivalent behaviour)
Throw(symbol.tpe, Literal(Constant("My Message")))
Throw(NEW(symbol, Literal(Constant("My message"))))
Throw(New(symbol.tpe, Literal(Constant("My message"))))
But I got an exception:
== Enclosing template or block ==
Apply( // val <error>: <error> in class <error>
new MyException.type."<init>" // val <error>: <error> in class <error>, tree.tpe=<error>
Nil
)
== Expanded type of tree ==
TypeRef(TypeSymbol(class MyException extends ))
uncaught exception during compilation: scala.reflect.internal.Types$TypeError
error: scala.reflect.internal.Types$TypeError: MyException.type does not have a constructor
...
I suppose I somehow have to use "new" differently, does anyone know how this is done correctly?