简体   繁体   English

Java:将所有方法参数获取为对象数组

[英]Java: get all method parameters as Object array

Is it possible to do this: 是否有可能做到这一点:

void foo(Bar b, FooBar fb){
    Object[] args=getArgs() //Contains the parameters b & fb
}

And if yes, how? 如果是的话,怎么办?

(I dont know the name and the number of parameters) (我不知道参数的名称和数量)

No, Java does not support a simple, generic way to pack all the method arguments into an array. 不,Java不支持将所有方法参数打包到数组中的简单通用方法。 This is pretty standard for statically typed programming languages. 对于静态类型的编程语言,这是相当标准的。 It's generally dynamic languages like JavaScript and shell scripting languages that do allow retrieving all the arguments as an array. 通常,动态语言(如JavaScript和Shell脚本语言)确实允许将所有参数作为数组检索。

Given a method like you declare it, there is no (easy/standard) way to retrieve it as an Object[] . 给定像您声明它的方法,没有(简单/标准)方法可以将其检索为Object[]

Now, you can always declare a method as 现在,您始终可以将方法声明为

public void doSomething(Object... args) {
   Object o1 = args[0];  // etc
}

then you can call 那你可以打电话

doSomething(foo);
// or
doSomething(foo, bar, baz);

but you lose all type safety doing it this way; 但是这样做会失去所有类型的安全性; I don't really recommend it. 我真的不推荐它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM