I have a code:
Model.java:
public abstract class Model <T> {
public static <T> T find(int id) {
T result = (T) blackMagicMethod(T.class, id);
return result;
}
}
, User.java
public class User extends Model<User> {
}
, Main.java:
public class Main {
public static void main(String[] args) {
System.out.println(User.find(1));
}
}
, blackMagicMethod:
public Object blackMagicMethod(Class clazz, int id) {}
The line blackMagicMethod(T.class, id) don’t work, like any hacks described in Getting the class name from a static method in Java.
How can I make this code working?
The class of a generic type is not available in runtime, i.e.
T.classdoes not make sense.The generic types gets translated to
Objecton compilation. This is what’s called Type Erasure.If you really need the
classof the type argument, you’ll need to add that as an argument: