Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Represent a Java type as a varargs

Is it possible 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");
}
like image 774
rnunes Avatar asked Mar 11 '26 17:03

rnunes


2 Answers

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"));
like image 94
henko Avatar answered Mar 13 '26 07:03

henko


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"));
like image 23
Bozho Avatar answered Mar 13 '26 07:03

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!