The Class
class takes a generic parameter. So rather than passing Class cls
, pass Class<T> cls
.
public <T> List<T> getTouchingObjects(Class<T> cls){
List<T> thing;
//fill thing
return thing;
}
This allows you to specify the return type, in terms of the class passed as a parameter. The implementation, will still most likely be using introspection.
Of course as it is this can still allow clients to pass a class that is nonsensical to your context. I guess whatever your method does, it won't be applicable to Strings, yet nothing prevents calling getTouchingObjects(String.class)
. You haven't specified what type those touching objects have generally, but for the sake of example I'll assume they ought to be subclasses of ChessPiece
. In that case you'd narrow the method down like this :
public <T extends ChessPiece> List<T> getTouchingObjects(Class<T> cls){
List<T> thing;
//fill thing
return thing;
}
Like that, calling getTouchingObjects(String.class)
won't even compile, and you've improved your type safety even more.