如何在Java中将对象数组作为参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2805989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:02:16  来源:igfitidea点击:

How to pass object array as parameter in Java

javaarraysobjectparameter-passing

提问by derrdji

The method is public static void method(Object[] params), how should I call it in the following scenarios?

方法是public static void method(Object[] params),在以下场景中应该如何调用?

  1. with one object as parameter ClassA a
  2. with more than one objects as parameters ClassA a, ClassB b, ClassC c? thank you
  1. 以一个对象作为参数 ClassA a
  2. 以多个对象作为参数ClassA a, ClassB b, ClassC c? 谢谢你

采纳答案by aioobe

You can create the array of objects on the fly:

您可以动态创建对象数组:

method(new Object[] { a, b, c});

Another suggestion is that you change the signature of the method so that it uses java varargs:

另一个建议是更改方法的签名,以便它使用 java varargs:

public static void method(Object... params)

Nice thing is that it is compiled into a method with the same signature as above (Object[] params). But it may be called like method(a)or method(a, b, c).

不错的是,它被编译成一个与上面具有相同签名的方法(Object[] params)。但它可能被称为 likemethod(a)method(a, b, c)