[英]How can I determine amount of constructor parameters for a generic type using reflections in java?
I need to determine how many arguments a constructor accepts during runtime in a generic method. 我需要确定泛型方法中构造函数在运行时接受多少个参数。 I know every type T extends the same baseclass and they only have one constructor each, but they take different amount of parameters. 我知道每个类型T都扩展相同的基类,并且每个类型都只有一个构造函数,但是它们采用的参数数量不同。
public T someMethod() {
// get amount of parameters T constructor takes
}
Is there a simple way of achieving this? 有没有简单的方法可以实现这一目标?
No. Due to type erasure , there is no way to find out anything about T
from a method with that signature. 不会。由于类型擦除 ,无法从具有该签名的方法中找到有关T
任何信息。
If you change the method to accept a type token , then yes: 如果将方法更改为接受类型令牌 ,则可以:
public T someMethod(Class<T> clazz) {
// eg:
Constructor<?>[] constructors = clazz.getConstructors();
// eg:
constructors[i].getParameterTypes();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.