【问题标题】:is it possible assign different return type for method是否可以为方法分配不同的返回类型
【发布时间】:2013-10-26 20:57:10
【问题描述】:

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

我的机会是:

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

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

如果有办法我可以在验证器中存储返回类型并使用它?

【问题讨论】:

  • 您这样做的愿望通常表明存在更深层次的设计问题。
  • 验证来自用户的数据是常见的问题。可以使用任何更好的设计吗?如果它是 python,我的解决方案简单易用。但我对 java 关闭了。

标签: java generics


【解决方案1】:

对于您的第一点,如果演员阵容不合适,则无法在运行时获得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.

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

【讨论】:

  • 我以前读过泛型和继承。我习惯了python风格。 Xmmm 在类对象中发现了有趣的方法作为强制转换。会期待的。
  • 有用且彻底的 +1 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 2022-07-17
  • 2015-07-19
  • 1970-01-01
相关资源
最近更新 更多