我正在用 Java 语言开发一个web-app,它由一个系统和一些模块组成。所有这些都实现了IAppIdentifier
接口,我将所有模块引用和系统本身存储在List
系统中。
我们的想法是以这样的方式设计:每个模块都能够访问系统本身或其他模块(如果它们具有所需的接口(从IAppIdentifier扩展)),因此他们必须向系统询问它们。
我的代码有效:
@Override
public IAppIdentifier moduleByClass(Class<? extends IAppIdentifier> clazz) {
List<IAppIdentifier> iApps = this.get_Iapps();
for (IAppIdentifier iApp : iApps) {
if (clazz.isAssignableFrom(iApp.getClass())) {
return iApp;
}
}
return null;
}
基本上它检查数组中的每个类是否都可以从所需的接口分配,如果是,它将返回该实例。但问题是我必须在方法返回时抛出它。
例如,我必须实现类似的东西来获取系统的实例:
((ISystem) this.get_Service().moduleByClass(ISystem.class))
我的问题是,在java中是否有任何方法可以避免再次执行该转换,以确保它将返回与我在编译时作为参数传递的相同类型?
答案 0 :(得分:5)
将方法签名更改为:
public <T extends IAppIdenfitier> T moduleByClass(Class<T> clazz)
这应该有用。
即使您的interface
不是通用的,您仍然可以在方法中使用泛型来实现自己的目的。通过此代码,您可以提供T
必须为IAppIdentifier
本身或必须扩展它的通用规则。您的方法现在将返回T
类型的对象,并将其作为参数类Class<T>
。
然后在您调用方法moduleByClass
的代码中,您不必强制转换它,例如:
ISystem = this.get_Service().moduleByClass(ISystem.class);
这里不需要施放,一切都会编译。
根据@XtremeBiker的好评,需要更多信息。在moduleByClass
方法内部,需要将结果类型转换为T
。所以它是:
return iApp;
但现在应该是:
return clazz.cast(iApp);
无论如何,在调用该方法时,每次在方法体内进行强制转换时,它仍然不那么烦人。