I have a badly created container object that holds together values of different java types(String, Boolean etc ..)
public class BadlyCreatedClass {
public Object get(String property) {
...;
}
};
And we extract values from it in this way
String myStr = (String) badlyCreatedObj.get("abc");
Date myDate = (Date) badlyCreatedObj.get("def");
I am forced to write some new code using this object and I am trying to see if there is clean way to do this. More specifically which method from the below is preferred ?
Explicit Cast
String myStr = (String) badlyCreatedObj.get("abc")
Date myDate = (Date) badlyCreatedObj.get("def");
Using generic cast
public <X> X genericGet(String property) {
}
public String getString(String property) {
return genericGet(property);
}
public Date getDate(String property) {
return genericGet(property);
}
Using Class.cast
<T> T get(String property, Class<T> cls) {
;
}
I have gone through several related questions on SO Java generic function: how to return Generic type , Java generic return type all of them seem to say the such typecasting is dangerous, ALthough I dont see much difference between the three, given this which method would you prefer ?
Thanks