Java 在方法返回中强制使用整数而不是int

Java 在方法返回中强制使用整数而不是int,java,wrapper,Java,Wrapper,我有一组方法读取属性值并返回整数、浮点或字符串中的值 接下来的问题是: 如果开发人员这样做: int value = prop.getValueInteger("id.property"); 如果该方法没有找到属性或有NumberFormatException,我将返回null。在这种情况下,赋值失败,出现NullPointerException。与方法Float版本相同(包含字符串,因为它们不使用原语) 我知道程序员可能会被迫捕获可能的异常,但我建议如果有任何选项可以强制开发人员使用整数而不

我有一组方法读取属性值并返回整数浮点字符串中的值

接下来的问题是:

如果开发人员这样做:

int value = prop.getValueInteger("id.property");
如果该方法没有找到属性或有NumberFormatException,我将返回null。在这种情况下,赋值失败,出现NullPointerException。与方法Float版本相同(包含字符串,因为它们不使用原语)


我知道程序员可能会被迫捕获可能的异常,但我建议如果有任何选项可以强制开发人员使用整数而不是整数。

为了防止开发人员只分配给
int
,当您有一个可能不存在的值时,您可以返回
可选的

这假设您不能抛出像这样更有用的异常

public int getValueInteger(String name) throws IllegalStateException {
     Object v = getValue(name);
     if (v == null) throw new IllegalStateException("Property " + name + " not set.");
     return convertTo(Integer.class, v);
}

不,自动取消装箱只是Java作为一种语言的一个特性。你不能禁用它。+1但没有太大的区别,只是给程序员一个提示。他仍然可以做
int value=prop.getValueInteger(“id.property”).get()@CarlosHeuberger的确如此。我看到了
可选。orElse(null)
您可以绕过它,但它会鼓励开发人员考虑它。这是一个很好的响应,无论如何,我已经用默认值重载了方法的版本。我喜欢选修课type@Genaut您可以使用
optional.orElse(defaultValue)
来支持默认值。
int value = prop.getValueInteger("id.property", -1);
public int getValueInteger(String name) throws IllegalStateException {
     Object v = getValue(name);
     if (v == null) throw new IllegalStateException("Property " + name + " not set.");
     return convertTo(Integer.class, v);
}