gpt4 book ai didi

java - 设计类/接口(interface)以支持返回不同类型的方法

转载 作者:行者123 更新时间:2023-11-29 06:21:14 25 4
gpt4 key购买 nike

我有如下类(class)。

public interface ITest <T>
{
public Set<T> methodHere();
}

public class test1 implements ITest<String>
{
Set<String> methodHere(){
return // Set of String
}
}

public class test2 implements ITest<Integer>
{
Set<Integer> methodHere(){
return // Set of Integer
}
}

public class ITestFactory {
public static ITest getInstance(int type) {
if(type == 1) return new test1();
else if(type == 2) return new test2();
}
}
public class TestUser {
public doSomething(int type) {
ITest t = ITestFactory.getInstance(type);
if(type == 1) Set<Integer> i = t.methodHere();
else if(type == 2) Set<String> s = t.methodHere();
...
}
}

工厂类中有一个警告,指出 ITest 被用作原始类型。我应该做些什么修改来摆脱它?

TestUser 代码看起来很难看。我错过了一些非常基本的东西吗?我不想使用 Set<?>

谢谢奈恩

最佳答案

您可以返回一个 ITest<?>摆脱警告,但可能你想要一个更强类型的方法:

public class TestFactory {
public static ITest<?> getInstance(int type) {
if(type == 1)
return new test1();
else if(type == 2)
return new test2();
else
throw new IllegalArgumentException("Unknown type");
}

public static <T> ITest<T> getInstance(Class<T> clazz) {
if(clazz == String.class)
return new test1();
else if(clazz == Integer.class)
return new test2();
else
throw new IllegalArgumentException("Unknown type");
}
}

关于java - 设计类/接口(interface)以支持返回不同类型的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2949131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com