我们可以在运行时从泛型类型实例化一个对象吗? 我有一个类:
MyClass<T> implements SomeInterface<T> {
..
public T someMethod() {
return <object of Type T> // Desired!!!
}
..
}
或者假设我从需要泛型类型实例的其他类调用此方法:
TestMayClass {
DesiredClass t = new MyClass<DesiredClass>().someMethod();
// Can I have generics type at run time and construct object from it then return to calling method? Manipulating generic type??
}
:此代码未编译,只是虚构的代码,具有类似的方式。
最佳答案
不,你不能在 Java 中做到这一点。即使我们输入 type erasure另外,编译器怎么知道调用的构造函数存在?
Java 中最能满足您要求的东西是 reflection .
关于java - 我们可以在运行时从泛型类型实例化一个对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31985245/