Java 是否可以为方法指定不同的返回类型
我的想法是有一个验证器接口,它有方法Java 是否可以为方法指定不同的返回类型,java,generics,Java,Generics,我的想法是有一个验证器接口,它有方法getRealValue()。返回值取决于字段,它可以是String、Integer或Long值 我的机会是: 我可以将返回类型指定为Object,并在每次调用此方法后使用强制转换。(RuntimeError如果发生错误的强制转换) 我可以在实例化验证器时使用泛型的pass返回类型(我仍然必须使用casting,但在方法getRealValue中只能使用一次)。如果我忘记传递返回类型或传递错误类型,仍然RuntimeError 如果有一种方法可以将返回类型存储
getRealValue()
。返回值取决于字段,它可以是String
、Integer
或Long
值
我的机会是:
Object
,并在每次调用此方法后使用强制转换。(RuntimeError
如果发生错误的强制转换)getRealValue
中只能使用一次)。如果我忘记传递返回类型或传递错误类型,仍然RuntimeError
如果有一种方法可以将返回类型存储在验证器中并使用它?对于您的第一点,在运行时无法获得一个
ClassCastException
,以防不适当的强制转换
在第二种情况下,不需要强制转换,请参见以下示例:
public interface Foo<T> {
public T getValue();
}
公共接口Foo{
公共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.
public类Blah实现了Foo{
@凌驾
公共T getValue(){
//要写代码吗
//注意,由于类型擦除,您将不知道这里是什么类型的t
返回null;
}
}
。。。然后,在其他地方:
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.
Blah blah1=新Blah();
字符串s=blah1.getValue();
废话废话2=新废话();
//等等。
最后,这里有一些文学作品给你:
- 在爪哇
- 在Java中(有关于铸造的部分)