【发布时间】:2019-07-23 15:35:05
【问题描述】:
我有多个 AbstractAsset 类的实现
我想根据 type 选择资产 impl。 我设法通过继承和
@JsonSubTypes
问题是,在一对资产中,我已经拥有相同的类型字符串,这使得它
@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = TitleAssetDTO.class, name = "TITLE"),
@JsonSubTypes.Type(value = VideoAssetDTO.class, name = "VIDEO"),
@JsonSubTypes.Type(value = ImageAssetDTO.class, name = "IMAGE"),
@JsonSubTypes.Type(value = DataAssetDTO.class, name = "DATA")
})
@AllArgsConstructor
@NoArgsConstructor
public abstract class AbstractAssetDTO {
@NotNull private String type;
@NotNull private String key;
}
例如
public class TitleAssetDTO extends AbstractAssetDTO {
private Title title;
public Title getTitle() {
return title;
}
public void setTitle(Title title) {
this.title = title;
}
public TitleAssetDTO() {
this.title = new Title();
}
@Data
public class Title {
private Integer maxLength;
}
@JsonIgnore
public int getMaxLength() {
return title.maxLength;
}
}
问题是其他资产类型作为它们在 json 中的类型字符串,所以我认为使用继承不是解决这个问题的正确方法,复合如下:
class myClass{
String type;
AbstractAsset asset;
}
这将是一个更好的实现方式,我该怎么做?
【问题讨论】:
-
你能创建一个简单的例子吗?什么不起作用以及如何重现它?
myClass有什么问题吗?如果asset已经有type并且您不需要复制它,为什么要添加type。