我写这将通过它尝试了class.cast验证属性的通用方法,但我不断收到一个ClassCastExceptionClassCastException异常使用Class.cast使用泛型
...类来测试
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异常。
任何想法非常赞赏。
不错的解决方法,如果没有该签名的构造函数,[NoSuchMethodException](http://docs.oracle.com/javase/6/docs/api/java/lang/NoSuchMethodException.html)被抛出女巫似乎在你的代码中处理。 – A4L 2013-03-26 20:58:42