我有这样的情况:
我有一个看起来像这样的类:
public class TestClass<T> {
// class body here...
}
我有一个看起来像这样的方法:
public class AnotherTestClass<K> {
private TestClass<K> testClass;
public AnotherTestClass(TestClass<K> testClass) {
this.testClass = testClass;
}
public K testMethod() {
//call methods on param object and pass a value of the same type as testClass.
K returnVal = this.testClass.doSomething();
return returnVal;
}
}
现在我有一个工厂方法,它返回一个 TestClass<?>
类型的对象
public TestClass<?> sampleFactory(int i) {
if( i==1 )
return new TestClass<Integer>();
if( i==2 )
return new TestClass<Double>();
if( i==3 )
return new TestClass<String>();
}
但我不能使用该方法将参数传递给我的 testMethod
.解决方案是什么?
目前我正在写if else
链 block 以获得正确的实例。我知道它不正确,因为写 if else
不切实际当有多个参数时会阻塞,如上所示。
请为此提出一个优雅的方法。
编辑:示例用法:
package my;
import java.util.ArrayList;
import java.util.List;
public class GenericsSpike {
public static void main( String[] args ) {
TestClass1< ? > tc1 = new TestClass1<Integer>( 123 );
TestClass2< ? > tc2 = new TestClass2<Integer>( 123 );
AnotherTestClass< ? > atc = new AnotherTestClass<Integer>( tc1, tc2 );
atc.testMethod();
}
}
class TestClass1<T> {
private T value;
TestClass1( T val ) {
value = val;
}
// class body here...
public T getValue() {
return value;
}
}
class TestClass2<T> {
private T value;
TestClass2( T val ) {
value = val;
}
// class body here...
public T getValue() {
return value;
}
}
class AnotherTestClass<K> {
public TestClass1<K> testClass1, testClass2;
public AnotherTestClass( TestClass1<K> testClass, TestClass2<K> testClass2 ) {
this.testClass1 = testClass;
}
public K testMethod() {
//Any logic can come here.
System.out.println( testClass1.getValue() );
System.out.println( testClass2.getValue() );
return testClass1.getValue();
}
}
在这种情况下,如果 tc1
和 tc2
来自创建这些对象的工厂,我想知道创建 AnotherClass
实例的正确方法是什么
最佳答案
你的问题出在这个方法上:
public TestClass<?> sampleFactory(int i) {
?
通配符类型的意思是“某种类型,但我不知道是什么”。所以你可以得到一个 TestClass<?>
类型的值,但它对您没有用,因为您无法与类型 ?
进行有意义的交互-- 你不能创建 ?
类型的值(null 除外)并且您不能调用 ?
类型的方法(java.lang.Object
的方法除外)。
你真正想要的是这样的:
public <T> TestClass<T> sampleFactory(TypeToken<T> typeToken) {
也就是说,如果你想让你的工厂返回给你不同类型参数化的值,你需要给它一些东西来告诉它你想要什么类型。不幸的是,int
还不够——您可能知道 i==1
表示类型将为 Integer
,但编译器不知道。
你对问题的描述有点太模糊了,我无法理解你真正想要实现的目标,但我猜你真正需要的是 super type tokens 之类的东西。或者像 Guava 的 ClassToInstanceMap
.
关于Java 泛型 -> 函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18162790/