How can I create a generic class, which takes the class type from the generic type argument that is placed when creating/injecting this generic class?
My goal is to specify eg MyGeneric<User>, and the generic class should then be capable to use the User class in all method calls. Without having to explicitly supplying User.class in the constructor of the generic additionally.
Something like:
class MyGeneric<T> {
public MyGeneric() {
someService.create(Class<T>, someString);
}
}
class Usage {
@Inject
MyGeneric<User> myuser;
}
How is this done propertly?
What you can do is write the instantiation code in a superclass and then extend it for each particular generic type (little or no code is required in subclasses, but the subclasses are mandatory as they’re the only way to avoid type erasure):
Edit: made the generic class
abstractto enforce the usage of subclasses.It can also be used with anonymous classes like:
new MyGeneric<User>("..string...") {}I think this is the closest to your initial goal you can get…