我正在编写一个通用方法,它将通过在其上尝试 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。
任何想法都非常感谢。