To add to the answers already mentioned here, if you have a generic class that handles, say, HTTP calls, it maybe useful to pass Class<T>
as part of the constructor.
To give a little more detail, this happens because Java cannot infer the Class<T>
during runtime with just T
. It needs the actual solid class to make the determination.
So, if you have something like this, like I do:
class HttpEndpoint<T> implements IEndpoint<T>
you can allow the inheriting code to also send the class<T>
, since at that point is it clear what T is.
public HttpEndpoint(String baseurl, String route, Class<T> cls) {
this.baseurl = baseurl;
this.route = route;
this.cls = cls;
}
inheriting class:
public class Players extends HttpEndpoint<Player> {
public Players() {
super("http://127.0.0.1:8080", "/players", Player.class);
}
}
while not entirely a clean solution, it does keep the code packaged up and you don't have to Class<T>
between methods.