我有一个类应该接受不同的数据类型作为第二个构造函数参数:
public abstract class QueryMatch {
String key;
Object input;
public <T> QueryMatch(String key, T o) {
this.key = key;
input = o;
}
public String getKey() {
return key;
}
public Object getValue() {
return input;
}
}
我不想使用类型参数,例如
public abstract class QueryMatch<T>{
String key;
T input;
...
这样,当我将检索 QueryMatch 声明为泛型时,我会收到原始类型警告(因为我不知道它包含的数据类型)。但问题是我需要返回该值,并且我对返回一个对象感到不太舒服(只是我这样,但这似乎不是一个好的做法?)。
此外,另一个类继承自它:
public class QueryMatchOr extends QueryMatch {
public QueryMatchOr() {
super("title", new ArrayList<String>());
}
public void addMatch(String match) {
((ArrayList<String>) input).add(match);
}
}
当然,我收到了 Unchecked 强制转换警告(我可以使用 @SuppressWarnings(“unchecked”) 来避免该警告)。
所以,我的问题是......有没有更好的方法来实现我想要做的事情?一个包含对象(可以有界)的抽象类,并返回它包含的数据类型(而不是对象),而不在类声明中使用类型参数?
最佳答案
你所做的不是一个好的设计。您正在使用父类(super class)中的 Object
类型字段,而您只能知道它在子类中的实际(需要)类型。如果只知道在子类中,则在子类中声明该变量。更不用说您的字段不是私有(private)的。
怎么样:
public abstract class QueryMatch {
private String key;
public QueryMatch(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public abstract void addMatch(String match);
}
public class QueryMatchOr extends QueryMatch {
private ArrayList<String> input;
public QueryMatchOr() {
super("title");
input = new ArrayList<String>();
}
public void addMatch(String match) {
input.add(match);
}
}
如果您需要父类(super class)中的 getValue()
方法,您确实应该将其设为通用:
public abstract class QueryMatch<T> {
private String key;
public QueryMatch(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public abstract void addMatch(String match);
public abstract T getValue();
}
public class QueryMatchOr extends QueryMatch<ArrayList<String>> {
private ArrayList<String> input;
public QueryMatchOr() {
super("title");
input = new ArrayList<String>();
}
public void addMatch(String match) {
input.add(match);
}
public ArrayList<String> getValue(String match) {
input;
}
}
关于java - 从抽象类返回 Java 上的通用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18786093/