Java中的泛型是否有类型安全且更简洁的替代方案?

时间:2015-05-08 20:18:35

标签: java generics overloading

我发现仿制品有助于通过去除铸件来促进概括和促进类型安全。但有时我觉得生成的代码对于附加值来说要大得多。是否存在避免多余的泛型代码且类型安全性没有退化的特殊情况?

例如,我有一个小的不变实用程序,除其他外,它检查复合对象(例如字符串集合或字符串)是否为空。如果未保留不变量,则实用程序会引发预定义的异常。对于类对象的类型使用泛型来避免强制转换看起来很诱人。

public interface Invariant<T> {
    void enforce(@SuppressWarnings("unchecked") T... arg) throws RuntimeException;
}

public class StringNotEmpty implements Invariant<String> {
    @Override
    public void enforce(String... arg) throws RuntimeException {
        for (int i = 0; i < arg.length; i++) {
            if (arg[i].trim().isEmpty()) {
            throw new IllegalArgumentException();
        }
    }
}

public class CollectionNotEmpty<T> implements Invariant<T extends Collection> {
    @Override
    public void enforce(@SuppressWarnings("unchecked") T... arg) throws RuntimeException {
        for (int i = 0; i < arg.length; i++) {
            if (arg[i].isEmpty()) {
            throw new IllegalArgumentException();
        }
    }
}

以下是使用不变实用程序的方法:

public void aMethod(String aString, String bString, List<Integer> aList) {
    Invariant<String> inv1 = new StringNotEmpty();
    Invariant<? extends List<Integer> inv2 = new CollectionNotEmpty<List<Integer>>();

    // Throw runtime exception when invariant1 is not kept
    inv1.enforce(aString, bString);

    // Do some business...

    // Throw runtime exception when invariant2 is not kept
    inv2.enforce(aList);
}

最终结果是平庸:不变量是令人满意的,并且类型安全性受到损害:请参阅supress-warnings注释,这只是masks冒险尝试使用varargs模板。

&#34;不变&#34; API可以更简洁,但保持其类型安全吗?

0 个答案:

没有答案