Represent a Java type as a varargs
Is it poss开发者_StackOverflow中文版ible to do something like this using Java features?
class myClass {int i; String s;}
static void myMethod(myClass... args)
{
...
}
main()
{
myMethod(2,"two",3,"three");
}
It is not possible. Perhaps you could create a static helper method which makes creating your objects as easy as possible.
static myClass mc(int i, String s) {
return new myClass(i, s);
}
myMethod(mc(2, "two"), mc(3, "three"));
No, but you can make a constructor of MyClass
and invoke:
myMethod(new MyClass(2, "two"), new Myclass(3, "three"));
For the sake of brevity you can make a statically-imported factory method:
public class MyClass {
public MyClass create(String s, int i) {
return new MyClass(s, i);
}
}
and use:
myMethod(create(2, "two"), create(3, "three"));
You could do it with a wrapper class:
class MyWrapper {
private int i;
private String s;
public MyWrapper(int _i, String _s) {
i = _i;
s = _s;
}
}
class Test {
static void myMethod(MyWrapper... args) {
//do work
}
public static void main(String[] args) {
myMethod(new MyWrapper(2, "two"), new MyWrapper(3, "three"));
}
}
Yes, sortof. You need a constructor of your class...
public class MyClass{
int i
String s;
public MyClass(int i, String s){
this.i = i;
this.s = s;
}
}
public static void myMethod(MyClass... instances){
.....
}
public static void myMethod(Object... args){
MyClass[] instances = new MyClass[args.length / 2];
for (int i=0; i<args.length / 2; i++){
instances[i] = new MyClass((Integer)args[i * 2], (String)args[(i*2) + 1]);
}
myMethod(instances);
}
You would need to add error checking to ensure that args has an even number of elements and there is not a method to enforce that every i * 2 element is an Integer and every i * 2 + 1 is a String. But it is possible.
Given all of the above, I will say... this is very non-standard programming and I would not recommend it. But as you see, it is possible.
精彩评论