Reed Oei
Reed Oei

Reputation: 1518

Scala: Proper way to get name of class for an object?

I have a class that contains a main method, and I wish to start a new process that runs this class.

But when I try to use Scala to get the name of this class, it gives me the wrong name. For example:

object Test {
  def main(args: Array[String]) = { 
    println(Test.getClass.getCanonicalName)
  }
}

Then:

roei@roei-main:~/Java$ scalac Test.scala 
roei@roei-main:~/Java$ scala Test
Test$
roei@roei-main:~/Java$ javap Test*.class
Compiled from "Test.scala"
public final class Test {
  public static void main(java.lang.String[]);
}
Compiled from "Test.scala"
public final class Test$ {
  public static final Test$ MODULE$;
  public static {};
  public void main(java.lang.String[]);
}

Test.getClass.getCanonicalName gives me Test$, not Test. But the static main method is inside of a class named Test, whereas Test$ contains a non-static main. Obviously I can do the workaround of just deleting the $ at the end, but I'm looking for a more satisfying/reliable solution.

Upvotes: 3

Views: 3249

Answers (1)

P3trur0
P3trur0

Reputation: 3225

A possible solution would be using ClassTag of scala.reflect (see API). I mean something like the following:

import scala.reflect.ClassTag
import scala.reflect.classTag

class Test

object Test {
  def main(args: Array[String]) = { 
    println(Test.getClass.getCanonicalName)
    println(classTag[Test].runtimeClass.getCanonicalName)
  }
}

it will print:

Test$  
Test

Upvotes: 5

Related Questions