Java 在地图中使用对象和强制转换的替代方法
我有一个表示一组属性的类Java 在地图中使用对象和强制转换的替代方法,java,generics,casting,Java,Generics,Casting,我有一个表示一组属性的类 public class Properties { /** String type properties. */ private final List<String> m_stringProperties = Arrays.asList("str1", "str2", "str3"); /** Float type properties. */ private final List<String> m_float
public class Properties
{
/** String type properties. */
private final List<String> m_stringProperties = Arrays.asList("str1", "str2", "str3");
/** Float type properties. */
private final List<String> m_floatProperties = Arrays.asList("float1", "float2", "float3");
/** Integer type properties. */
private final List<String> m_intProperties = Arrays.asList("int1", "int2");
public class PropertyType
{
private final String m_name;
private final Object m_value;
public PropertyType(String name, Object value)
{
m_name = name;
m_value = value;
}
public String getName()
{
return m_name;
}
public Object getValue()
{
return m_value;
}
}
/** The container for the properties. */
private final Map<String, PropertyType> m_properties = new HashMap<>();
public PropertyType getProperty(String name)
{
return m_properties.get(name);
}
public void setProperty(String name, Object value)
{
if ((m_stringProperties.contains(name) && value instanceof String)
|| (m_floatProperties.contains(name) && value instanceof Float)
|| (m_intProperties.contains(name) && value instanceof Integer))
{
m_properties.put(name, new PropertyType(name, value));
}
else
{
assert false : "Invalid property name";
}
}
}
我想知道是否有更好的方法来实现这一点。具体地说,我希望避免使用对象
及其附带的强制转换。我已经试验过参数化类和泛型类型,甚至一个类型安全的异构容器,如有效Java的第20项所述
我希望尽可能使其类型安全-即由编译器强制执行类型检查-以便如果调用getProperty
,则返回值自动为正确的类型
我意识到我可以为每个类型重载setProperty
,并且getProperty
可以只返回对象而不是嵌套类型PropertyType
,但这仍然会给我留下一个
的容器
<>我是来自C++的java新手。在C++中,map值将是一个<>代码>::变量> ,以确保该类将接收3种类型之一,编译器将使用它,可以使用一些多态性。
例如:
public PropertyType(String name, String value)
{
m_name = name;
m_value = value;
}
public PropertyType(String name, Integer value)
{
m_name = name;
m_value = value;
}
public PropertyType(String name, Float value)
{
m_name = name;
m_value = value;
}
字符串、整数和浮点扩展了对象,因此不需要将它们强制转换为变量private final Object m_值代码>
但是,如果您需要在执行类型中检查变量的类型(例如,create和variable,但不知道它是否是这三种类型中的一种),这可能不起作用
public PropertyType(String name, String value)
{
m_name = name;
m_value = value;
}
public PropertyType(String name, Integer value)
{
m_name = name;
m_value = value;
}
public PropertyType(String name, Float value)
{
m_name = name;
m_value = value;
}