4

我喜欢在 java 中创建数据库表的类表示。列被设计为通用类,以便它可以处理表列可能具有的所有不同数据类型。

public class TableColumn<T> {
    ...
}

一个表有 0 ... n 个 TableColumns,所以我的表类看起来像这样:

public class Table {
    protected ArrayList<TableColumn<T>> columns =
                new ArrayList<TableColumn<T>>();
    ...
}

这个想法是通过以下方式添加列。

Table t = new Table();
t.addColumn(String.class);
t.addColumn(Integer.class);
t.addColumn(Date.class);
t.addColumn(String.class);

然后我可以通过以下方式操作数据:

String a = t.Cols(2).Row(3);
t.Col(2).Row(3) = "b";

但是我目前的实现方式正在失去类型安全性......我的问题是如何实现列,因为列可能会获得不同的数据类型。

有人有线索吗?

4

2 回答 2

0

If there is a limited amount of Type combinations you could use interfaces to be those combinations. This would allow you to be able to store the column in the same way, and you wouldn't need any special casting.

t.addColumn(MyInterface.class);

Another method, which would still wouldn't be quite as clean as what you want but is kind of unavoidable, is to use a new Class that allows you to take the burden of some of the casting and type checking away.

Example:

public static class MyWrapper{
    Class<?>[] validPossibleClasses;
    Object o;
    public MyWrapper(Class<?> ...classes){
        this.validPossibleClasses = classes;
    }
    public boolean validateClass(Class<?> clazz){
        for (Class<?> c : validPossibleClasses){
            if (!c.isAssignableFrom(clazz))
                return false;
        }
        return true;
    }
    public void set(Object o) throws Exception{
        if (!validateClass(o.getClass()))
            throw new Exception("Bad Cast");
        this.o = o;
    }
    public String getString(){
        return (String) o;
    }
    public Integer getInt(){
        return (Integer) o;
    }
    ...
    // more specific getters
}

The usage would be like this

String a = t.Cols(2).Row(3).getString();
t.Col(2).Row(3).set("b");
于 2013-06-05T15:24:13.690 回答
0

为什么不为您拥有的每个表创建一个不同的对象?就像是:

具有字段的类玩家:

String name;
int points;
int number;

带田野的班级体育场:

String location;
Date dateBuilt;

具有领域的班级团队:

String name;
ArrayList<Players> roster;

然后,您可以将所有值保存在列表或数组列表中,并将它们由数据库表分隔,而不必猜测您在哪个表中。您必须保留更多对象,但您将能够知道更多你正在处理的事情。

于 2013-06-05T15:25:46.717 回答