4

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?

0

1 Answer 1

13

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.