Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Inheritance Kotlin域类转换为子类_Inheritance_Kotlin - Fatal编程技术网

Inheritance Kotlin域类转换为子类

Inheritance Kotlin域类转换为子类,inheritance,kotlin,Inheritance,Kotlin,我有一个域类 @Entity @Table(name = "user") open class User( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) open var id: Long = 0L, @Column(nullable = false) var name: String? = null) 我有一个域类的子类,我想添加一个JsonIgnore注释: open class U

我有一个域类

@Entity
@Table(name = "user")
open class User(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    open var id: Long = 0L,

    @Column(nullable = false)
    var name: String? = null)
我有一个域类的子类,我想添加一个JsonIgnore注释:

open class UserFiltered(
    @Id
    @JsonIgnore
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    override var id: Long = 0L
): User()
但当我尝试将用户强制转换为UserFiltered时:

return ResponseModel<UserFiltered>(true, userModified as UserFiltered)
return ResponseModel(true,userModified为UserFiltered)
我得到以下错误:

java.lang.ClassCastException: 无法将com.example.platform.database.domain.User强制转换为 com.example.platform.model.UserFiltered位于 com.example.platform.controller.UserController.modifyUser(UserController.kt:71) ~[classes/:na]


有没有办法在Kotlin中实现这一点,或者我必须进行完整的转换,在用户上设置每个参数?

我必须将子类修改为以下形式:

open class UserFiltered(
    @Id
    @JsonIgnore
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    override var id: Long = 0L
): User(){
    constructor(user: User): this(user.id)
}
以及创建UserFiltered的实例

return ResponseModel<UserFiltered>(true, UserFiltered(userModified))
返回响应模型(true,UserFiltered(userModified))

您确定
userModified
是UserFiltered的实例吗?你能用创建
userModified
userModified
的代码编辑你的问题吗
User
User
的一个实例,但是当我想将它转换为
UserFiltered
时,我得到了错误。我以为科特林是在自作主张,但我找到了解决办法。我将在几分钟后发布。因此,本质上,您创建了一个“复制构造函数”,它接受基本用户类并创建一个
UserFiltered
实例。您的旧代码不起作用,因为
userModified
只是基类的一个实例,而不是
UserFiltered
类,因此无法将其转换为基类,因为编译器无法验证它们是否始终共享相同的成员。