java - 从抽象类返回 Java 上的通用对象

标签 java generics casting

我有一个类应该接受不同的数据类型作为第二个构造函数参数:

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/

相关文章:

c - 在 C 中实现通用交换宏

c# - 从通用对象列表中读取通用值

c# - 继承 Linq to SQL 类并转换 linq 查询的结果

c# - 将继承的类转换回基类

c++ - 如何将接口(interface)对象转换为特定的继承对象

java - 带有绘制正方形的 JPanel 无法正确显示

java - 如何在 Linux 和 Windows 上使用 JOGL 设置 IntelliJIdea 进行开发?

java - Mapstruct 可选映射

java - 向 JavaFX 折线图添加不连续点

Java 泛型 : How to avoid casting in this example of java 2D generic arrays?