简体   繁体   中英

programmatically determine generic type

apologies if this is a duplicate.

Is there any way to determine what generic type a class is?

ie I want to know what T is....

public void doSomething(SomeClass<T> thing)
{
    Class<T> t = ???;
}

thanks, p.

Not in Java. You will have to accept a parameter of Class<T> too, which the caller will have to supply. (You can do this in the constructor if you would like, so that the class reference will be available to all class methods.) This is a commonly used hack to determine what T refers to at runtime, which is not available otherwise due to the way Java implements generics.

You can do this so long as T is parameterized by a class definition . Ex:

interface IContainer<T> {
  public void doSomething(SomeClass<T> thing) {
    Class<?> t = TypeResolver.resolveArgument(getClass(), IContainer.class);
  }
}

class ConatinerImpl implements IContainer<String> {}

See TypeTools for more info on using TypeResolver.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM