I am writing a generic method which will validate a property by trying a class.cast on it but I keep getting a ClassCastException
... Class to Test
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;
}
... Test Class
@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);
}
}
The code at commented at MARKER is causing the ClassCastException.
Any ideas much appreciated.