我正在尝试创建一个私有(private)方法,如果为其他方法传入的任何值都为 null,则抛出异常,无论传入的参数类型如何。所以说在构造函数中您下面有以下代码:
public void add(int num) {
exceptionCreator(num);
}
public void print(String something) {
exceptionCreator(something);
}
public void gamePiece(customObject blah) {
exceptionCreator(blah);
}
private void exceptionCreator([A type that works with all of them] sample) {
if(sample == null) {
throw new IllegalArgumentException();
}
}
如何使其适用于不同类型而不创建一堆类似参数的抛出?
最佳答案
int
不是引用类型,因此不能为 null
。您的另外两个(String
和 customObject
[应为 CustomObject
])是引用类型,因此它们可以为 null
.
所有引用类型的基类型都是Object
,因此这就是您想要的exceptionCreator
。虽然用 int
调用它是可行的(因为自动装箱),但它是没有意义的,因为它永远不会抛出异常。
所以:
public void add(int num) {
// Possible but pointless; it will never throw
exceptionCreator(num);
}
public void print(String something) {
exceptionCreator(something);
}
public void gamePiece(CustomObject blah) {
exceptionCreator(blah);
}
private void exceptionCreator(Object sample) {
if (sample == null) {
throw new IllegalArgumentException();
}
}
关于java - 如何传递多种类型的参数以在 "throw exception"方法中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37496668/