简体   繁体   English

Scala:在伴侣对象中获取伴侣类

[英]Scala: Get companion class in companion object

I need to define a val in my companion object which is initialized with a method which takes the companion class as parameter. 我需要在我的伴侣对象中定义一个val,它用一个以伴侣类作为参数的方法初始化。

I want to handle this with traits to not repeat myself. 我想用特征处理这个问题,不要重复自己。 My Problem ist, that X.getClass ist not the same as classOf[X]. 我的问题是,X.getClass与classOf [X]不同。 The first is the class of the companion object and the second is the class of the companion class, but I need to get the companion class without hardcoding it directly. 第一个是伴随对象的类,第二个是伴侣类的类,但我需要获取伴侣类而不直接对其进行硬编码。

Basically I need something like this: 基本上我需要这样的东西:

trait Foo {

}

object FooCompanionObject[f <: Foo] {
    val fClazz = classOf[f]
}

// Bar's fClass should be classOf[Bar]
case class Bar extends Foo;

object Bar extends FooCompanionObject[Bar];

The problem is that I cannot get the class of an generic type due to type erasure 问题是由于类型擦除,我无法获得泛型类

There are several problems in your code. 您的代码中存在几个问题。 First, as you already said, the type will be erased, second object s ( object FooCompanionObject[f <: Foo] ) don't take type parameters and third, object s can not be extended ( object Bar extends FooCompanionObject ). 首先,如您所说,类型将被删除,第二个object s( object FooCompanionObject[f <: Foo] )不采用类型参数,第三, object s不能被扩展( object Bar extends FooCompanionObject )。 To do what you want, you have to create an abstract base class for your companion objects, that takes a type parameter, which may be constrained to a specific type if you like, and has to be context bound on ClassTag . 要做你想做的事,你必须为你的伴侣对象创建一个抽象基类,它接受一个类型参数,如果你愿意,它可以被约束到一个特定的类型,并且必须在ClassTag上进行上下文绑定。 From the ClassTag you can then get the runtime class by calling runtimeClass on it. ClassTag然后你可以通过调用获取运行时类runtimeClass就可以了。 The final solution could look like this: 最终解决方案可能如下所示:

import scala.reflect.ClassTag
import scala.reflect.classTag

trait Foo

abstract class Companion[A <: Foo : ClassTag] {
  val fClazz = classTag[A].runtimeClass
}

class Bar extends Foo
object Bar extends Companion[Bar]


scala> Bar.fClazz
res2: Class[_] = class Bar

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

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