gpt4 book ai didi

java - 如何发送任意数量和类型的参数

转载 作者:行者123 更新时间:2023-12-02 01:15:27 24 4
gpt4 key购买 nike

我有一个非常基本的 Java 问题。为了将任意数量的参数从一种方法发送到另一种方法,我们可以使用 varargs 。但是,这仅在参数类型相同时才有效。我想知道是否有任何方法可以将任意数量和类型的参数从一种方法发送到另一种方法。例如,我想要一个方法首先发送 int 的 5 个参数的混合物。和String类型。稍后,同样的方法需要能够发送 Boolean 的混合的 7 个参数。 , String , chardouble类型。有什么方法可以执行这样的任务吗?谢谢。

最佳答案

I am wondering is there any way to send an arbitrary number and types of arguments from one method to another.

您可以使用Object... args :

void method(Object... args) {
// ...
}

int , char , double和其他基元类型参数将被包装在其对象包装器中( IntegerCharacterDouble )。

Live Example

import java.util.Arrays;

class Example {
void method(Object... args) {
System.out.println(Arrays.toString(args));
}
public static void main(String[] args) {
Example e = new Example();
e.method(1, "foo", 2, "bar", 3);
e.method(true, "foo", 'c', 'd', new Boolean(false), false);
}
}

关于java - 如何发送任意数量和类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58690787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com