我有两个A和B类.A有一个方法,比如说foo,可以有任意类型的任意数量的参数。该方法将这些参数传递给具有预定数量的预定类型的参数的方法。
Class A{
foo(<?> ... params){
(new B()).bar(params);
}
}
Class B{
bar(int a, int b){
Log.v("The params passed are "+a+" and "+b);
}
}
Class Caller{
callingMethod(){
(new A()).foo(1, 2);
}
}
我知道编译器不允许我为foo写下的签名;我写这篇文章只是为了解释我想要实现的目标。
我不想在B类栏(int,int)中进行任何投射。
答案 0 :(得分:2)
你可以使用变量参数......
public static void foo(Object... parameters ){
}
答案 1 :(得分:1)
您可以添加有限数量的参数,这些参数在varargs之前已修复。
这是在EnumSet
我已更改为foo
方法以接受3个参数E e1, E e2, E... params
,这可确保我至少有2个参数来调用bar(e1, e2)
方法。
<E extends Number>
确保您可以传递Number
Integer
的任何子类恰好是一个。
static class A {
<E extends Number> void foo(E e1, E e2, E... params) {
(new B<E>()).bar(e1, e2);
}
}
static class B<E extends Number> {
public void bar(E a, E b) {
}
}
public static void main(String[] args) {
A name = new A();
name.foo(1, 2, 123);
}
答案 2 :(得分:1)
正如其他人所建议的那样,您可以接受可变数量的Object
s作为函数参数。棘手的一点是解压缩,以便在bar
上调用B
。我已经汇总了一个如何使用反射来做到这一点的例子:
import java.lang.reflect.Method;
public class test {
static class A {
private final Class cl;
A(Class cl) {
this.cl = cl;
}
void foo(Object ... params) throws Exception {
Object obj = cl.newInstance();
for (Method m : cl.getMethods()) {
if (m.getName().equals("bar")) {
try {
m.invoke(obj, params);
return;
}
catch(IllegalArgumentException ex) {} // try next overload
}
}
throw new IllegalArgumentException();
}
}
static class B {
public void bar() {
System.out.println("Got nothing");
}
public void bar(double a, double b) {
System.out.println("Got doubles");
}
public void bar(int a, int b) {
System.out.println("Got: " + a + " and " + b);
}
}
public static void main(String argv[]) throws Exception {
new A(B.class).foo(1,2);
new A(B.class).foo();
new B().bar(1,2);
new A(B.class).foo("Hello");
}
}
但是你会注意到重载决议在这里远非完美,并且通过1,2
调用double,double
的{{1}}重载。要解决这个问题,你需要通过与你给出的每个对象的bar
最佳匹配来对Method
个对象的数组进行排序,但就我所知,这远非微不足道。
答案 3 :(得分:0)
Java中的Varargs:
foo(Object... objs) {}
示例:
public static void main(String... args) {}
相当于
public static void main(String[] args) {}
Nota:只要方法签名中没有剩余的参数,它就相当于使用数组。