I’m developing a web-app in Java language, which is composed by a system and some modules. All of them implement the IAppIdentifier interface and I have all the module references and the system itself stored in a List into the system.
The idea is to design that in such way that every module will be able to access the system itself or another modules if they have the required interface (extended from IAppIdentifier), so they have to ask the system for them.
I have this code which works:
@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;
}
Basically it’s checking that each class from the array is assignable from the required interface and if it is it will return that instance. However the matter is that I have to cast it when it’s returned by the method.
For example I have to implement something like that to obtain system’s instance:
((ISystem) this.get_Service().moduleByClass(ISystem.class))
My question is, is there any way in java to avoid doing that casting again, ergo, to ensure it will return the same type I’m passing as argument at compile time?
Change method signature to this one :
This should work.
Even if your
interfaceisn’t generic you can still use generics in methods for they own purpose. By this code you provide generic rule thatThas to beIAppIdentifieritself or has to extend it. Your method now will return object of typeTand take as param class asClass<T>.Then in your code whenever you invoke method
moduleByClassyou don’t have to cast it, for example:Cast won’t be needed here and everything will compile.
There is more info needed according to @XtremeBiker good comment. Inside
moduleByClassmethod it’s needed to cast resulting type toT. So it was:But now it should be:
Anyway it’s still less annoying to make cast in on place inside method body than doing it everytime when that method is invoke.