简体   繁体   English

以编程方式确定泛型

[英]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.... 即我想知道T是什么...

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

thanks, p. 谢谢,第

Not in Java. 不是用Java。 You will have to accept a parameter of Class<T> too, which the caller will have to supply. 您还必须接受Class<T>的参数,调用者必须提供该参数。 (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. (您可以根据需要在构造函数中执行此操作,以便所有类方法都可以使用该类引用。)这是一种常用的技巧,可以确定T在运行时所指的是什么,否则由于Java实现泛型的方式。

You can do this so long as T is parameterized by a class definition . 只要T由类定义参数化, 就可以执行此操作。 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. 有关使用TypeResolver的更多信息,请参见TypeTools。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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