英文:
Is it possible to cast returned value before returning?
问题
我听说过泛型,但是我找不到一种让它返回已转换值的方法。
例如:
public <T> T getController(SceneEnum sceneEnum) {
if (sceneData.get(sceneEnum) == null) {
initScene(sceneEnum);
}
return sceneData.get(sceneEnum).getLoader().getController();
}
这个方法返回不同的类,比如 MainScreenControler
,PopupController
等等。
但是我不能在不进行类型转换的情况下调用返回类的方法。
- 可行:
((MainScreenController)getController(MainScreenEnum)).someMethod(); - 不可行:getController(MainScreenEnum).someMethod();
所以有没有办法在获取器内部执行类型转换呢?
英文:
I heard about generic, but I can't find a way to make it return already casted value.
For example:
public <T> T getController(SceneEnum sceneEnum) {
if (sceneData.get(sceneEnum) == null) {
initScene(sceneEnum);
}
return sceneData.get(sceneEnum).getLoader().getController();
}
this method returns different classes, for example MainScreenControler, PopupController etc.
but I can't call method from returned class, without casting it.
- works:
((MainScreenController)getController(MainScreenEnum)).someMethod(); - doesn't work: getController(MainScreenEnum).someMethod();
So is there any way to perform casting inside getter?
答案1
得分: 2
尝试明确指定泛型类型
在包含getController
方法的类内部:
this.<MainScreenController>getController(MainScreenEnum).someMethod();
或者在不同的类内部:
instance.<MainScreenController>getController(MainScreenEnum).someMethod();
(这里instance
是包含getController
方法的类的实例)。
不幸的是,这几乎比以下写法没有更短:
((MainScreenController) getController(MainScreenEnum)).someMethod();
由于T
是在调用点而不是定义点决定的,所以你不能在getter内部进行“强制转换”操作。
英文:
Try to specify generic explicitly
this.<MainScreenController>getController(MainScreenEnum).someMethod();
inside the class containing getController
or
instance.<MainScreenController>getController(MainScreenEnum).someMethod();
inside a different class (instance
is an instance of the class containing getController
).
Unfortunately, this is hardly shorter than
((MainScreenController) getController(MainScreenEnum)).someMethod();
You can't "cast" inside getter because T
is decided in a call site, not in the definition site.
答案2
得分: 2
这里是一种使用泛型进行安全类型转换的方法:
public <T> T getController(SceneEnum sceneEnum, Class<T> clazz) {
if (sceneData.get(sceneEnum) == null) {
initScene(sceneEnum);
}
Object controller = sceneData.get(sceneEnum).getLoader().getController();
if (clazz.isInstance(controller)) {
return (T) controller;
} else {
throw new ClassCastException("类型转换失败");
}
}
英文:
Here's a method of casting safely with generics:
public <T> T getController(SceneEnum sceneEnum, Class<T> clazz) {
if (sceneData.get(sceneEnum) == null) {
initScene(sceneEnum);
}
Object controller = sceneData.get(sceneEnum).getLoader().getController();
if (clazz.isInstance(controller)) {
return (T) controller;
} else {
throw new ClassCastException("Failed to cast");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论