我想通过杰克逊(Jackson)解析YAML文件,但是遇到一个问题,即其中一个属性(我们称其为“事件”)具有一个名为“ type”的字符串和一个针对不同事件而有所不同的“ properties”对象。我的问题是我需要为此YAML定义POJO。因此,我想用VariableObject定义一个Hashmap,它可以是某些预定义的类中的任何一个(为简便起见,假设是Shipping和Inventory)。
如何实现这样的Hashmap?
public class Event {
private static String type;
private static Map<String, VariableObject> properties;
public static void main(String[] args) {
Inventory inventory = new Inventory("inventoryName", 13);
properties.put("Inventory", inventory);
Shipping shipping = new Shipping("shippingName", true);
properties.put("Shipping", shipping);
}
}
public class Inventory {
private static String name;
private static int someNumber;
public Inventory(String name, int someNumber) {
this.name = name;
this.someNumber = someNumber;
}
}
public class Shipping {
private static String name;
private static boolean someBoolean;
public Shipping(String name, boolean someBoolean) {
this.name = name;
this.someBoolean = someBoolean;
}
}
答案 0 :(得分:2)
您要说的是简单的Object
。这是最具体的普通超类:
private static Map<String, Object> properties;
其他解决方案是使Inventory
和Shipping
实现一些通用接口,例如Named
,并将其用作HashMap
中的类型参数。
答案 1 :(得分:1)
一种方法是使Shipping
和Inventory
实现相同的接口(例如cas中的VariableObject
)
public class Event {
private static String type;
private static Map<String, VariableObject> properties;
public static void main(String[] args) {
Inventory inventory = new Inventory("inventoryName", 13);
properties.put("Inventory", inventory);
Shipping shipping = new Shipping("shippingName", true);
properties.put("Shipping", shipping);
}
}
public interface VariableObject{
//you can define common methods here if you want
}
public class Inventory implements VariableObject{
private static String name;
private static int someNumber;
public Inventory(String name, int someNumber) {
this.name = name;
this.someNumber = someNumber;
}
}
public class Shipping implements VariableObject{
private static String name;
private static boolean someBoolean;
public Shipping(String name, boolean someBoolean) {
this.name = name;
this.someBoolean = someBoolean;
}
}