我的想法是有一个 validator 接口(interface),它有方法getRealValue()
。返回值取决于字段,可以是String
、Integer
或Long
值。
我的机会是:
我可以将返回类型指定为
Object
并在每次调用此方法后都使用转换。 (RuntimeError
如果发生错误转换)。在实例化 validator 时,我可以使用通用的传递返回类型(我仍然必须使用转换,但在方法
getRealValue
内,并且只能使用一次)。如果我忘记传递返回类型或传递错误的类型,仍然是RuntimeError
。
是否有一种方法可以将返回类型存储在 validator 中并使用它?
最佳答案
对于您的第一点,如果转换不当,则无法在运行时获取 ClassCastException
。
在你的第二种情况下你不需要转换,看这里的例子:
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.
最后,这里有一些文学给你:
- Generics在 java
- Inheritance在 Java 中(有一个关于类型转换的部分)
关于java - 是否可以为方法分配不同的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19442475/