Java: get the total value of a parameter at runtime

What is the best way to get the runtime value of a generic parameter for a generic class? For example:

public class MyClass<T> {

  public void printT() {
    // print the class of T, something like:
    // System.out.println(T.class.getName());
  }

}

So if I call

new MyClass<String>().printT() 

it will output "String"

+3
source share
4 answers

No. Due to the erasure type, this information is (mostly) lost at runtime. If you really need a class, this is what you do:

public class MyClass<T> {
  private final Class<T> clazz;

  public MyClass(Class<T> c) {
    if (c == null) {
      throw new NullPointerException("class cannot be null");
    }
    clazz = c;
  }

  public void printT() {
    System.out.println(clazz.getName());
  }
}

and then you have access to it.

+6
source

To do this, you need to add type information, since deleting the type means that the type is Tnot available.

public class MyClass<T> {
  private final Class<T> clazz;
  public MyClass(Class<T> clazz) {
    this.clazz=clazz;
  }

  public void printT() {
    // print the class of T, something like:
    System.out.println(this.clazz);
  }
}
+1
source

Java , - erasure. . , : Guice , Scala .

+1

, - .

, / :

package com;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;

public class AAA {
    public static void main(String[] args) throws Exception {
        Object target = new MyClass<Integer>() {}; // child class that explicitly defines superclass type parameter is declared here
        ParameterizedType type = (ParameterizedType) target.getClass().getGenericSuperclass();
        System.out.println(Arrays.toString(type.getActualTypeArguments()));
    }
}

class MyClass<T> {
}
0

Source: https://habr.com/ru/post/1720161/


All Articles