Passing varargs to another method as different type
I refactored one of my classes. It should be made serializable. It has a method foo with a parameter of type object varargs.
It may look like:
public class MyClass {
public void foo(Object ... param) {
// do sth
}
}
And after the refactoring:
public class MyClass implements Serializable {
public void foo(Serializable ... param) {
// do sth
}
}
Now, there is another method calling foo and passing its object varargs.
public void bar(Object ... param) {
foo(param);
}
At this point, I expected to get an error for passing an Object[] to Serializable[]. In fact, if it would be arrays over varargs, I would.
But instead it will wrap the object varargs into a serializable array. foo receives a serializable array with 1 element, that is an object array with the passed varargs.
Why is this happening? How can I force this wrong usage to actually throw an error at compile-time?
(I am using eclipse neon with Java 1.8
Serializable...
will take any number of arguments as long as they're all serializable.
Arrays are serializable.
So, it's not going to raise compiler errors (note that because Java is statically typed, it won't be a runtime error).
What you can do is check in foo
what the argument is, and if param.length == 1 && param[0] instanceof Object[]
then throw an error. That's probably the best you can do.
Solved it by changing the parameter type from varargs to array:
public void foo(Serializable[] param) { }
// called like this
foo(new Serializable[] { param1, param2, param3 } );
// or this
public void bar(Serializable[] param) {
foo(param);
}
This way I regain the type safety at compile time without additional overhead for checking that the varargs parameter is serializable.
Although the manual wrapping of the serializable array adds some noise to the code, this seems to be the best compromise for my case.
链接地址: http://www.djcxy.com/p/78962.html上一篇: Gruntjs:为什么编译scss来清空文件? 使用咕噜声
下一篇: 将可变参数作为另一种类型传递给另一种方法