Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the class name from a generic static method in Java

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?

like image 604
Timothy Klim Avatar asked Dec 12 '22 05:12

Timothy Klim


1 Answers

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;
    }
}
like image 147
aioobe Avatar answered Jan 17 '23 00:01

aioobe