英文:
Is there a way to allow only an Int parameter of a function within a Range
问题
我正在尝试找出一种方法,在调用给定函数时限制整型参数,只要整型值在某个特定范围内。
例如:
class A{
void doSomething(int nValueWithin10And214){}
}
class B{
A objA = new A();
objA.doSomething(int someValue) //在这里已经知道参数的限制
}
我已经知道在函数内部检查参数是否在范围内,但我正在寻找一种在调用方已经知道限制的方法。
我应该在这些情况下创建一个自定义的可抛出对象,当参数不在范围内时,调用方会抛出异常吗?
还是应该创建一个继承自整型的自定义对象,使得被调用的函数和调用方已经符合要求?
哪种方式是推荐的?
有什么想法吗?
英文:
I am trying to figure out a way to limit an int parameter when calling a giving function as long as the int value is within a certain range.
For example:
class A{
void doSomething(int nValueWithin10And214){}
}
class B{
A objA = new A();
objA.doSomething(int someValue) //Here already know the limitation of the parameter
}
I already know to check inside the function if the parameter is within a range, but I'm looking a way when the caller already knows the limitation.
Should I create a custom throwable in these cases and the caller throws an exception when it's not within the range?
Should I create a custom object extending an Integer so the function called and the caller already comply with the requirements?
What would be the recommended way?
Any thoughts?
答案1
得分: 0
在Java SE
中,默认情况下无法限制方法参数的可能值范围;然而,有一些Bean Validation
框架可能会帮助您实现所需的功能。Hibernate的Validator
(Bean Validation参考实现)是一个非常流行的框架,您可以进行参考。
但是,并没有这样的规范被实现到Java核心语言中。
英文:
No, there is no way, in Java SE
, to limit by default, your method parameter's possible values' range; however, there are some Bean Validation
framework(s), which might help you to achieve your desired functionality. Hibernate's Validator
(The Bean Validation reference implementation) is one very popular framework you can reference.
But no, no such a specification has ever been implemented to Java core language.
答案2
得分: 0
这种情况下,我认为最好的方法是在参数超出范围时抛出异常,就像你自己提到的那样。就像这样:
void doSomething(int nValueWithin10And214) {
if (nValueWithin10And214 < 10 || nValueWithin10And214 > 214) {
throw new ValueNotInRangeException();
}
}
英文:
I think the best way to do this is by throwing an exception if the parameter is outside the range, as you mentioned yourself. Like this:
void doSomething(int nValueWithin10And214){
if (nValueWithin10and214 < 10 || nValueWithin10and214 > 214 {
throw new ValueNotInRangeException();
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论