如何在Java中强制转换继承的对象

尼沙卡

在Java Spring Boot中接收继承的对象时,我遇到一个小问题。

class AbstractEntity{
    String type;
    Integer age;
}

class Animal extends AbstractEntity{
    String legs;
}

class Bird extends AbstractEntity{
    String flySpeed;
}

class Human extends AbstractEntity{
    String firstname;
    String lastname;
}

HumanBirdAnimal从被继承AbstractEntity现在,我从前端收到一个人类物体。我需要从中识别对象type

{
    type: "Human",
    age:30;
    firstname:"John",
    lastname: "Smith"
}

目前,我正在使用地图来识别

public void save(@RequestBody Map entity){
    
    if(entity.get("type").equalsIgnoreCase("Human")){
        Human h=new Human(entity.get("type"),entity.get("age"),entity.get("firstname"),entity.get("lastname"))
    }
    // same for Animal and bird
}

我无法在不知道控制器类型的情况下指定对象。如果我使用AbstractEntitylike收到对象,@RequestBody AbstractEntity entity则子字段将丢失。有没有比使用更简单,更好的方法Map

提前致谢

菲耶维姆

我建议您探索Jackson批注@JsonTypeInfo@JsonSubTypes以及@JsonTypeName

它将类似于:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
              include = As.PROPERTY, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Animal.class, name = "animal"),
    @JsonSubTypes.Type(value = Bird.class, name = "bird"),
    @JsonSubTypes.Type(value = Human.class, name = "human")
})
class AbstractEntity {
}

@JsonTypeName("animal")
class Animal extends AbstractEntity {
}

@JsonTypeName("bird")
class Bird extends AbstractEntity {
}

@JsonTypeName("human")
class Human extends AbstractEntity {
}

这只是一个基本示例,@JsonTypeName如果我没有记错的,还可以使用其他具有相同注释的方法,而无需定义

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章