3

我的想法是有一个验证器接口,它有方法getRealValue()。返回值取决于字段,它可以是StringIntegerLong

我的机会是:

  1. Object每次调用此方法后,我都可以将返回类型分配为并使用强制转换。(RuntimeError如果发生错误的铸造)。

  2. 我可以在实例化它时使用通用的传递返回类型到验证器(我仍然必须使用强制转换,但在方法内部getRealValue并且只有一次)。如果RuntimeError我忘记传递返回类型或传递错误的类型。

如果有一种方法可以将返回类型存储在验证器中并使用它?

4

1 回答 1

10

ClassCastException对于您的第一点,如果演员阵容不合适,则无法在运行时获得 a 。

在第二种情况下,您不需要强制转换,请参见此处的示例:

public interface Foo<T> {
    public T getValue(); 
}

...然后在其他地方:

public class Blah<T> implements Foo<T> {
    @Override
    public T getValue() {
        // TODO write the code
        // note that because of type erasure you won't know what type T is here
        return null;
    }
}

...然后,在其他地方:

Blah blah1 = new Blah<String>();
String s = blah1.getValue();
Blah blah2 = new Blah<Long>();
// etc.

最后,这里有一些文献给你:

于 2013-10-18T05:56:21.943 回答