我正在编写一个泛型方法,它将通过尝试使用class.cast来验证属性,但我不断获得ClassCastException
......要测试的课程
public <T> T get(Properties p, String propKey, Class<T> clazz) throws Exception {
T val = null;
Object propValue = p.get(propKey);
if(propValue== null) {
throw new Exception("Property (" + propKey + ") is null");
}
try {
val = clazz.cast(propValue); // MARKER
} catch(Exception e) {
throw new Exception("Property (" + propKey + ") value is invalid value of type (" + clazz + ")", e);
}
return val;
}
...测试类
@Before
public void setUp() {
propUtil = new PropUtil();
properties = new Properties();
properties.setProperty("test.int.prop", "3");
}
@Test
public void testGet() {
try {
assertEquals(new Integer(3), propUtil.get(properties, "test.int.prop", Integer.class));
} catch (Exception e) {
System.out.println(e);
}
}
MARKER注释的代码导致ClassCastException。
任何想法都非常感激。
答案 0 :(得分:3)
Properties
类是Hashtable
个存储String
个对象,尤其是当您调用setProperty
时。您添加了String
“3”,而不是整数3
。您实际上是在尝试将“3”转换为Integer
,以便正确抛出ClassCastException
。尝试
assertEquals("3", propUtil.get(properties, "test.int.prop", String.class));
或者如果您希望让get
返回Integer
,那么只需使用Hashtable<String, Integer>
,甚至更好,使用HashMap<String, Integer>
答案 1 :(得分:2)
假设此处Properties
为java.util.Properties
,则值始终为String
s。
你应该使用getProperty()
方法,而不是get()
恰好可以从HashTable
看到的{{1}}方法,因为这个类是在Java人员对构图不太谨慎时写的。继承。
答案 2 :(得分:1)
这一行
properties.setProperty("test.int.prop", "3");
在属性中放置java.lang.String
并将Integer.class
传递给您的通用方法。所以ClassCastException
是预期的!
如果你想测试Integer.class
,你必须放一个整数
properties.put("test.int.prop", 3);
请注意上面一行put类Properties的使用范围Hashtable
如果您打算放置String
并测试Integer
,那么您必须以某种方式parse将该字符串转换为整数值
答案 3 :(得分:0)
感谢您的回复。我意识到从String到Integer的基本行为是不可能的。我只是想让方法更加流畅并为我做转换检查。我刚刚使用Reflection解决了我正在寻找的解决方案:
Object propValue = p.get(propKey);
Constructor<T> constructor = clazz.getConstructor(String.class);
val = constructor.newInstance(propValue);
即使用带有String.class的公共构造函数(即String属性值)
努力享受。