jac*_*ver 19 java oop generics casting
我有一个创建严重的容器对象,它将不同java类型的值(String,Boolean等)保存在一起.
public class BadlyCreatedClass {
public Object get(String property) {
...;
}
};
Run Code Online (Sandbox Code Playgroud)
我们以这种方式从中提取价值
String myStr = (String) badlyCreatedObj.get("abc");
Date myDate = (Date) badlyCreatedObj.get("def");
Run Code Online (Sandbox Code Playgroud)
我被迫使用这个对象编写一些新的代码,我试图看看是否有干净的方法来做到这一点.更具体地说,下面哪种方法是优选的?
明确的演员
String myStr = (String) badlyCreatedObj.get("abc")
Date myDate = (Date) badlyCreatedObj.get("def");
Run Code Online (Sandbox Code Playgroud)
使用通用演员
public <X> X genericGet(String property) {
}
public String getString(String property) {
return genericGet(property);
}
public Date getDate(String property) {
return genericGet(property);
}
Run Code Online (Sandbox Code Playgroud)
使用Class.cast
<T> T get(String property, Class<T> cls) {
;
}
Run Code Online (Sandbox Code Playgroud)
我已经经历了几个关于SO Java泛型函数的相关问题:如何返回Generic类型,Java泛型返回类型所有这些似乎都说这样的类型转换是危险的,虽然我看不出三者之间有太大的区别,给定这个方法会你比较喜欢 ?
谢谢
为了快速给出答案,而不深入讨论良好的编程实践......
我会用:
private <X> X genericGet(String property) {
}
public String getString(String property) {
//... checks on property (String specific)...
Object obj = genericGet(property);
//... checks if obj is what is expected and if good return it
return obj;
}
public Date getDate(String property) {
//... checks on property (Date specific)...
Object obj = genericGet(property);
//... checks if obj is what is expected and if good return it
return obj
}
Run Code Online (Sandbox Code Playgroud)
请注意私有 genericGet。这样我就可以检查获取的属性是否是我正在等待接收的属性并以正确的方式处理它。
我可以在 getString 依赖属性中添加检查,以确保答案是 String 对象。
我可以对属性中的 getDate 进行其他检查,以确保它将是返回的日期。
ETC...