0

Possible Duplicate:
Scala equivalent of Java java.lang.Class<T> Object

Hi all,

I can not call a java classname.class method in scala, but scala guarantee that I can call any java method in scala, so why I can not call ClassName.class method

Jeff Zhang

Community
  • 1
  • 1
zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • 3
    See here: http://stackoverflow.com/questions/1135248/scala-equivalent-of-java-java-lang-classt-object – dlev May 25 '11 at 05:35

2 Answers2

4

T.class is actually not a method or a field but a special form that instructs the Java compiler that you are referring to the run-time representation of the class. The equivalent special form in Scala is classOf[T].

Your subject asks a different question, which is if you can call .getClass() for any object. The answer to that is yes, but that does something different --- for a given instance of a class T, it gives you T. So although in the end you still get the run-time representation T, the starting point is different --- an instance of T rather than a name/symbol representing T itself.

To put these ideas together, note that T.class.getClass() (or classOf[T].getClass in Scala) will always give you the runtime representation of java.lang.Class for any T. Amusingly, this is both the runtime representation of java.lang.Class, and also an instance of java.lang.Class itself since Java, unlike some languages, does not have metaclasses.

Gregory Crosswhite
  • 1,457
  • 8
  • 17
1

For a class A, just use classOf[A] instead to get the class object.

Sam Stainsby
  • 1,588
  • 1
  • 10
  • 19