简体   繁体   English

在java中使用scala泛型类

[英]Using a scala generic class in java

I have this in scala: 我在scala中有这个:

object Tester {
  def apply[T : Manifest](description: String, initValue: T) = new Tester[T](description, initValue)
  implicit def TesterToValue[T](j: Tester[T]): T = j.value
}

class Tester[T : Manifest](someData: String, initValue: T) {
  private var value = initValue
  def getValue : T = value
}

which allows me to do 这让我做到了

val t1 = JmxValue("some data", 4)

I'm trying to create an instance of this is java, so far I've had no luck I've tried: 我正在尝试创建一个这样的实例是java,到目前为止我没有运气我尝试过:

Tester t1 = Tester<Integer>("data", 0);
Tester<Integer> t1 = Tester<Integer>("data", 0);
Tester t1 = Tester("data", 0);
Tester t1 = new Tester<Integer>("data", 0);
Tester<Integer> t1 = new Tester<Integer>("data", 0);

Is there some limitation in using scala generic classes in java? 在java中使用scala泛型类是否有一些限制? Or am I just doing something horribly wrong 或者我只是在做一些可怕的错误

Your Tester class actually has an implicit parameter (because of the [T : Manifest] type boundary. The syntax you use is sugar for 你的Tester类实际上有一个隐含参数(因为[T : Manifest]类型边界。你使用的语法是sugar for

// Scala Class
class Tester[T](someData: String, initValue: T)(implicit man: Manifest[T]){...}

When that gets compiled, the two argument lists are condensed to one, so you end up with the java equivalent of 当编译时,两个参数列表被压缩为一个,所以你最终得到的是java的等价物

//Java Constructor
public Tester(String someData, T initValue, Manifest<T> man){...}

You can see the type signature by running the javap command on the Tester.class file that gets generated by the scala compiler. 您可以通过在Scala编译器生成的Tester.class文件上运行javap命令来查看类型签名。

So if you are trying to use the Tester class from Java, you have to explicitly figure out the parameter that scala's compiler would normally figure out for you. 因此,如果您尝试使用Java中的Tester类,则必须明确指出scala编译器通常会为您找出的参数。

Looking at the scaladocs, it looks like ManifestFactory is where you need to go to create Manifest instances. 看看scaladocs,看起来ManifestFactory就是你需要创建Manifest实例的地方。 So your java code would look something like 所以你的java代码看起来像

Manifest<Integer> man = ManifestFactory$.MODULE$.classType(Integer.class);
Tester<Integer> tester = new Tester<Integer>("data", 123, man);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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