简体   繁体   English

随播对象的类

[英]Companion object's class

How do i get the class that the companion object is representing? 我如何获得伴随对象代表的类? For Example: 例如:

val user = User("something")
val userClazz = user.getClass //returns somepackage.User

Now if i have a companion User object: 现在,如果我有一个伴随的User对象:

object User {
  def myClass = this.getClass //seems to return a different type of class somepackage.User$
}

My question is how do i get the "true" case classes class? 我的问题是如何获得“真实的”案例类类? I have an instance with reflection where this is causing me to get some strange "private" constructor while trying to use this.getClass inside of the companion object. 我有一个带有反射的实例,该实例使我在尝试在伴随对象内部使用this.getClass时得到一些奇怪的“私有”构造函数。

You can get the class of User with classOf[User] . 您可以使用classOf[User]获得User类。 Every (singleton) object has its own class. 每个(单个) object都有其自己的类。 Companion object User is not an instance of class User . 随播对象User不是User类的实例。

Generally, you can't obtain the companion class, because the companion class might or might not exist or be class-loaded. 通常,您无法获得伴随类,因为伴随类可能存在或可能不存在或已被加载。 Other than reflection, there is no way to do this in the language. 除了反思之外,没有其他语言可以做到这一点。

The recommended way is to declare a method in the companion object that returns the class, eg companionClass - this can be mandated with an interface that the object is extending. 推荐的方法是在伴随对象中声明一个返回类的方法,例如, companionClass可以使用对象扩展的接口来强制执行此方法。

Hate to answer my own question and i'd gladly mark someone else's the correct one if someone knows a better way but this is the hack i came up with for now and it seems to get me where i want to go. 讨厌回答我自己的问题,如果有人知道更好的方法,我很乐意将其他人标记为正确的人,但这是我目前想出的办法,它似乎可以使我找到想要去的地方。

val clazzName = this.getClass.getName
val clazz = Class.forName(clazzName.substring(0, clazzName.length - 1))

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

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