Scala equivalent of Java java.lang.ClassT Object
According to "The Scala Type System",
val c = new C
val clazz = c.getClass // method from java.lang.Object
val clazz2 = classOf[C] // Scala method: classOf[C] ~ C.class
val methods = clazz.getMethods // method from java.lang.Class<T>
The
classOf[T]
method returns the runtime representation for a Scala type. It is analogous to the Java expressionT.class
.
UsingclassOf[T]
is convenient when you have a type that you want information about, whilegetClass
is convenient for retrieving the same information from an instance of the type.
However, classOf[T]
and getClass
return slightly different values, reflecting the effect of type erasure on the JVM, in the case of getClass.
scala> classOf[C]
res0: java.lang.Class[C] = class C
scala> c.getClass
res1: java.lang.Class[_] = class C
That is why the following will not work:
val xClass: Class[X] = new X().getClass //it returns Class[_], nor Class[X]
val integerClass: Class[Integer] = new Integer(5).getClass //similar error
There is a ticket regarding the return type of getClass
.
(James Moore reports that the ticket is "now", ie Nov. 2011, two years later, fixed.
In 2.9.1, getClass
now does:
scala> "foo".getClass
res0: java.lang.Class[_ <: java.lang.String] = class java.lang.String
)
Back in 2009:
It would be useful if Scala were to treat the return from getClass() as a java.lang.Class[T] forSome { val T : C } where C is something like the erasure of the static type of the expression on which getClass is called
It would let me do something like the following where I want to introspect on a class but shouldn't need a class instance.
I also want to limit the types of classes I want to introspect on, so I use Class[_ <: Foo]. But this prevents me from passing in a Foo class by using Foo.getClass() without a cast.
Note: regarding getClass
, a possible workaround would be:
class NiceObject[T <: AnyRef](x : T) {
def niceClass : Class[_ <: T] = x.getClass.asInstanceOf[Class[T]]
}
implicit def toNiceObject[T <: AnyRef](x : T) = new NiceObject(x)
scala> "Hello world".niceClass
res11: java.lang.Class[_ <: java.lang.String] = class java.lang.String
Convert class parameter from Java to Scala
The equivalent of Java's T.class
in Scala would be classOf[T]
:
val connection = DriverManager.getConnection("jdbc: ...")
val olapConnection = connection.unwrap(classOf[OlapConnection])
Note: not tested as I'm not sure what are your dependencies.
What is the Java equivalent of a Scala object?
Support for singletons is not on a language level, but the language provides enough facilities to create them without any trouble.
Consider the following code:
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
This is an example from Wikipedia, which explains how a singleton can be made. An instance is kept in a private field, constructor is inaccessible outside the class, the method returns this single instance.
As for constructors: every class by default has a so-called default constructor which takes no arguments and simply calls the no-args constructor of the superclass. If the superclass doesn't have any accessible constructor without arguments, you will have to write an explicit constructor.
So a class must have a constructor, but you don't have to write it if the superclass has a no-args constructor.
What is the Scala equivalent of Java's ClassName.class?
There is a method classOf in scala.Predef
that retrieves the runtime representation of a class type.
val stringClass = classOf[String]
You can use the getClass
method to get the class object of an instance at runtime in the same manner as Java
scala> val s = "hello world"
s: String = hello world
scala> s.getClass
res0: Class[_ <: String] = class java.lang.String
Calling Java Generic Typed Method from Scala gives a Type mismatch error : Scala
Welcome to SO.
This seems to compile, but I am not sure if it works with the real implementation of JavaClass, but I am pretty sure it should.
import scala.reflect.ClassTag
object ScalaClass {
def toArray[T <: AnyRef](coll: java.util.Collection[T])(implicit ct: ClassTag[T]): Array[T] =
JavaClass.toArray[T](ct.runtimeClass.asInstanceOf[Class[T]], coll)
}
To call it from Scala you just need to pass the java collection, it would get the correct class from the type, like this:
val col: java.util.Collection[String] = ???
val array: Array[String] = ScalaClass.toArray(col)
Edit
If you want to preserve the original signature, you have to do this:
object ScalaClass {
def toArray[T <: AnyRef](t: java.lang.Class[T], coll: java.util.Collection[T]): Array[T] =
JavaClass.toArray[T](t, coll)
}
Which you can use like this:
val col: java.util.Collection[String] = ???
val array: Array[String] = ScalaClass.toArray(classOf[String], col)
In both cases the trick is the <: AnyRef
type bound.
IMHO, the first version is more ergonomic to be used on idiomatic Scala code.
How to get an java.lang.Class of a scala object for an annotation argument
classOf[MyObject$]
does not work because there is no type called MyObject$
.
In fact, the issue did come up before and there is no easy solution. See the discussion on https://lampsvn.epfl.ch/trac/scala/ticket/2453#comment:5
Related Topics
Functional Style of Java 8's Optional.Ifpresent and If-Not-Present
How to Disable Jsessionid in Tomcat Servlet
How to Add a New Line of Text to an Existing File in Java
How to Generate Cdata Block Using Jaxb
Invalid Thread Access Error with Java Swt
Spring: Why Do We Autowire the Interface and Not the Implemented Class
Jpa: Unidirectional Many-To-One and Cascading Delete
Hibernate Criteria: Joining Table Without a Mapped Association
Httpurlconnection Timeout Settings
Override Default Spring-Boot Application.Properties Settings in Junit Test
How to Import Spring-Config.Xml of One Project into Spring-Config.Xml of Another Project
How to Use Audio Sample Data from Java Sound
How to Set Request Encoding in Tomcat
Java, How to Add Library Files in Netbeans