I'm writing a storage manager. I want to read from file to object. Example:
protected Object read(String key) throws Exception{
Path pathReadFrom = Paths.get(getPath(key));
if (!Files.isReadable(pathReadFrom)){
throw new FileNotFoundException();
}
Object object = JSON_MAPPER.readValue(Files.readAllBytes(pathReadFrom), Object.class);
return object;
}
JSON_MAPPER is Jackson's ObjectMapper.
public MyClass get(String id) throws Exception {
MyClass myClassObject = (MyClass) storeManager.read(id);
return myClassObject;
}
I get the next exception:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.pckg.project.dto.MyClass
How can I create universal read() method? Maybe should I set a type like second argument of read() method?
I've thought up some solution:
protected <T> T read(String key, Class<T> valueType) throws Exception{
Path pathReadFrom = Paths.get(getPath(key));
T object = JSON_MAPPER.readValue(Files.readAllBytes(pathReadFrom), valueType);
return object;
}
public MyClass get(String id) throws Exception {
MyClass object = storeManager.read(id, MyClass.class);
return object;
}
It works fine.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments