简体   繁体   中英

Supplying “Class” type as a parameter to a method in Scala

I am exploring Scala by rewriting some of my Java code with it. In one of the Java method, I need to pass a class type as a parameter:

public void setType(Class<T> type)

In Java, I could do it by:

someobj.setType( MyClass.class )

But in Scala, I can't seem to call "MyClass.class". I am wondering how I can pass the parameter in Scala?

你是在classOf[MyClass]

scala> case class MyClass()
defined class MyClass

scala> def setType[T](t:Class[T]) = println(t)
setType: [T](t: Class[T])Unit

scala> setType(classOf[MyClass])
class $line23.$read$$iw$$iw$MyClass

Philippe correctly points out that the OP needs to call a Java method from Scala. In that case, more info about the java class is needed to determine intent, but something like this:

Java:

public class JavaClass<T> {
    public void setType(Class<T> type) {
        System.out.println(type);
    }
}

Scala:

class MyClass()
object classtest {
  val someobj = new JavaClass[MyClass]     //> someobj  : JavaClass[MyClass] = JavaClass@6d4c1103     
  someobj.setType(classOf[MyClass])               //> class MyClass
}

There's one more way to do so if you just need to pass class type and use it to model data or /create new instances.

def doSomeThing[T](id: UUID, time: Date): List[T] = {
// do anything with T, it's a reference to class definition not an instance
  List(T(id, time), T(id, new Date(time.getTime + 900 * 1000))
}
case class SomeClassA(id: UUID, time: Date)
case class SomeClassB(id: UUID, time: Date)
class NonCaseClass(p1: UUID, p2: Date)


doSomeThing[SomeClassA]()
doSomeThing[SomeClassB]()
doSomeThing[NonCaseClass]()

I have made this code little complex, here's the wrapper only example:

def doSomeThing[T]() = {
// do anything with T, it's a reference to class definition not an instance
}
case class SomeClassA(id: UUID, time: Date)

doSomeThing[SomeClassA]()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM