避免java中的强制转换(泛型)
这是一种避免下面的演员阵容的方法吗避免java中的强制转换(泛型),java,generics,Java,Generics,这是一种避免下面的演员阵容的方法吗 //Is there a way this can be implemented so the cast is not necessary? FooService fooService = new FooService(); Foo f = (Foo)fooService.findById(id); public class FooService extends DomainServiceImpl<Foo> { } public class
//Is there a way this can be implemented so the cast is not necessary?
FooService fooService = new FooService();
Foo f = (Foo)fooService.findById(id);
public class FooService extends DomainServiceImpl<Foo> {
}
public class DomainService<T extends Persistable>{
private Class<T> type;
public void findById(long id) {
domainDao.findById(id, type);
}
}
嗯,在这得到一个评论树之前,我会发布一个可能适合你需要的解决方案。然而,你必须根据你的具体问题调整它 主要思想是,方法
findById
返回泛型类型T
,因此不需要在代码中强制转换类型
class Solution {
static class Foo extends Persistable {
}
public static void main(String[] args) {
FooService fooService = new FooService();
Foo f = fooService.findById(0l);
}
static class FooService extends DomainService<Foo> {
FooService() {
type = Foo.class;
}
}
static class Persistable {
}
static class DomainService<T extends Persistable> {
Class<T> type;
public T findById(long id) {
try {
return this.type.newInstance();
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
类解决方案{
静态类Foo扩展了持久性{
}
公共静态void main(字符串[]args){
FooService=newfooservice();
Foo f=fooService.findById(0l);
}
静态类FooService扩展了DomainService{
食物服务(){
类型=Foo.class;
}
}
静态类持久化{
}
静态类域服务{
班级类型;
公共T findById(长id){
试一试{
返回此.type.newInstance();
}
捕获(实例化异常e){
抛出新的运行时异常(e);
}
捕获(非法访问例外e){
抛出新的运行时异常(e);
}
}
}
}
您可以使用:
type.cast(object);
为了避免警告
注意,这仍然可能引发ClassCastException
如果不确定对象是否可以强制转换,请检查:
if (type.isInstance(object)){
return type.cast(object);
} else {
...
}
是的,在findById方法中返回T,而不是像现在这样返回void。这是否可以编译?@Matthias你应该写这篇文章作为回答。我不确定这是唯一的问题,因为发布的代码中缺少类型。我看不出对此进行否决的意义question@user874774,不显示有错误的代码。它会分散用户对原始问题的注意力
if (type.isInstance(object)){
return type.cast(object);
} else {
...
}