如何通过对象数组作为Java参数 [英] How to pass object array as parameter in Java

查看:189
本文介绍了如何通过对象数组作为Java参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该方法公共静态无效的方法(对象[] PARAMS),我应该怎么称呼它在下列情况下?


  1. 一个对象作为参数 ClassA的一个

  2. 与多个对象作为参数 ClassA的一个 ClassB的b ClassCÇ
    谢谢


解决方案

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

 办法(新对象[] {A,B,C});

另一个建议是,你改变方法的签名,以便它使用Java的可变参数:

 公共静态无效的方法(对象... PARAMS)

好处是,它被编译成一个方法具有相同签名如上(对象[] PARAMS)。但它可以被称为像方法(一)办法(A,B,C)

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

  1. with one object as parameter ClassA a
  2. with more than one objects as parameters ClassA a, ClassB b, ClassC c? thank you

解决方案

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:

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).

这篇关于如何通过对象数组作为Java参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆