Cómo obtener el classOf para un tipo de objeto scala

I wonder how to get a class object for an object type in Scala. Ok, that is a mouth full because of the double meaning for object. So here an example which will fail:

object Main
{
   private [this] val TAG = classOf [Main].getName;
} // Main

If Main was class it works perfectly. Any ideas?

preguntado el 09 de marzo de 12 a las 14:03

3 Respuestas

scala> Main.getClass
res1: java.lang.Class[_] = class Main$

respondido 09 mar '12, 14:03

Yes. I see, now it becomes all clear. objects have exactly one instance and therefore you call getClass. Gracias. - Martin

@Martin Actually, I'd say that's incorrect. objects no tener instances at all, because they aren't types; they son the only instances of (compiler-generated) classes, and that's why you can call getClass. - Aleksey Romanov

Is their a Way to do this as a compile time Constant so that it can be used for a Java Annotation Attribute of type Class ? - Markus Knecht

@MarkusKnecht I don't know one; you may want to ask this as a separate question. - Aleksey Romanov

La razón por la cual classOf[Main] no funciona es porque Main no es un tipo.

Classes and traits define types, objects do not.

respondido 09 mar '12, 15:03

Since Main is an object, for your example to work, simply replace your assignment line with;

private [this] val TAG = this.getClass.getName;

respondido 09 mar '12, 14:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.