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.class
does not make sense.
The generic types gets translated to Object
on compilation. This is what's called Type Erasure.
If you really need the class
of the type argument, you'll need to add that as an argument:
public abstract class Model <T> {
public static <T> T find(Class<T> clazz, int id) {
T result = (T) blackMagicMethod(clazz, id);
return result;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With