jeudi 6 septembre 2018

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.





Aucun commentaire:

Enregistrer un commentaire