Reputation: 4827
I have a service layer method that I want to expose that should return an instance of an object that extends CMSContent (e.g. Delivery Time, Price). However, in method getCMSContent, the compiler is insisting that I do a cast to T. Is this cast below acceptable, or am I defeating the purpose of generics?
I compile with "-Xlint:unchecked" and receive no warnings, and it functions as I expect.
public <T extends CMSContent> T getCMSContent(String cmsKey, Class<T> clazz) {
T cmsInstance = (T) CMSObjectCache.getCachedCMSObject(cmsKey, clazz);
return cmsInstance;
}
This is the entire method of getCachedCMSObject
public static <T> T getCachedCMSObject(String objectKey, Class<T> cls) {
init();
CMSObject cmsObject = cmsObjectCache.get(objectKey);
if (cmsObject != null) {
return cmsObject.getCMSObject(cls);
}
return null;
}
Upvotes: 1
Views: 111
Reputation: 30022
Since the the signature of getCachedCMSObject
is:
T getCachedCMSObject(String cmsKey, Class<T> clazz)
your cast is to T
is unnecessary although you may want to throw an exception rather than return a null.
Upvotes: 1