如何在 Java 中创建一个接受任意数量任意类型参数的方法?

发布于 2025-01-07 07:18:29 字数 297 浏览 2 评论 0原文

我可以看到 Java 中有一种方法可以接受任意数量的指定类型的参数: http: //www.java-tips.org/java-se-tips/java.lang/how-to-pass-unspecified-number-of-arguments-to-am.html

但是有没有办法使一个接受任意数量任意类型参数的方法?

I can see there is a way to have a method in Java which accepts any number of arguments of a specified type:
http://www.java-tips.org/java-se-tips/java.lang/how-to-pass-unspecified-number-of-arguments-to-a-m.html

but is there a way to make a method which accepts any number of arguments of any type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

戏剧牡丹亭 2025-01-14 07:18:29

所有 Java 对象都扩展了 Object 类。所以你可以让你的函数接受一个对象数组:

public void func(Object[] args) {
}

或者如果你不想传递任何东西:

public void func(Object... args) {
}

All Java Objects extend the Object class. So you can make your function accept an Object array:

public void func(Object[] args) {
}

Or if you want to be able to pass nothing:

public void func(Object... args) {
}
内心荒芜 2025-01-14 07:18:29
public void omnivore(Object... args) {
   // what now?
}

在 Java 中,任何引用类型(对象和数组)的变量,包括某些泛型类型,甚至通配符,都可以传递给 Object 类型的参数。任何基本类型的变量都可以自动装箱为其相应的包装类型,该类型是引用类型,因此可以作为对象传递。因此,Object... 将接受任意数量的任何内容。

public void omnivore(Object... args) {
   // what now?
}

In Java, a variable of any reference type (objects and arrays), including ones of some generic type, even wildcards, can be passed to a parameter of type Object. A variable of any primitive type can be autoboxed to its corresponding wrapper type, which is a reference type, and so can be passed as Object. So, Object... will accept any number of anything.

娇纵 2025-01-14 07:18:29

使用这个语法:

void myMethod(Object... args) {
    // Here, args is an array of java.lang.Object:
    // you can take its length, get its elements with [i] operator,
    // and so on.
}

Use this syntax:

void myMethod(Object... args) {
    // Here, args is an array of java.lang.Object:
    // you can take its length, get its elements with [i] operator,
    // and so on.
}
温馨耳语 2025-01-14 07:18:29

您将得到的最接近的是someMethod(Object ... args)

严格来说,这不接受所有参数类型。具体来说,它不接受原始类型:这些类型需要装箱到相应的包装类型。通常这没有什么区别。但如果您需要在被调用方法中区分原始类型和包装类型,则需要这样做。

The closest you will get is someMethod(Object ... args).

Strictly, this does not accept all argument types. Specifically, it does not accept primitive types: these need boxed to the corresponding wrapper types. Normally this makes no difference. But it does if you need to distinguish between primitive and wrapper types in the called method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文