我有一个这样的情况:
我有一个类,看起来像这样:
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
链块来获取正确的实例。我知道这样做是不正确的,因为当像上面那样有多个参数时,编写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
实例的合适方式是什么。
if/else
的摘录吗? - user180100testMethod
的返回值是什么?method
不是一个有效的返回类型;你是想说void
吗?如果它是一个void方法,那么可能testMethod
中的K
没有任何好处,你可以只接受一个TestClass<?>
。但这都是猜测。更有可能的是,你需要纠正你的工厂,因为拥有一个在编译时未知的泛型类型的泛型工厂是无用的。 - Mark PeterstestMethod
中添加了一个注释,但那不是我要求的。我要求的是使用testMethod
和sampleFactory
的示例代码。几乎总是,如果类型参数只在运行时知道,将testMethod
泛型化并没有什么好处,因为K
永远不会在编译时解析为任何内容。缺乏好的答案表明你的问题缺乏上下文(尽管它获得了奇怪数量的赞)。 - Mark Peters