java 不固定参数,在Java构造函数中有固定的参数 - 可能吗?

I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

public MenuNode(int type = 1, param1, param2, param3) {

doStuffHere();

}

public MenuNode(int type = 2, paramX, paramY) {

doStuffHere();

}

and then call something along the lines of:

switch (toQueue.itemType) {

when ITEM_TYPE_STATIC {

MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);

}

when ITEM_TYPE_DYNAMIC {

MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);

}

}

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.

If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

解决方案

Another approach is to avoid using a constructor here, and create a static factory method which calls a private constructor:

class MenuNode {

private MenuNode() {

// Does nothing important

}

public static MenuNode createStatic(param1, param2, param3) {

MenuNode result = new MenuNode();

result.setItemType(ITEM_TYPE_STATIC);

result.setParam1(param1);

result.setParam2(param2);

result.setParam3(param3);

result.doStuffHere();

return result;

}

public static MenuNode createDynamic(paramX, paramY) {

MenuNode result = new MenuNode();

result.setItemType(ITEM_TYPE_DYNAMIC);

result.setParamX(paramX);

result.setParamY(paramY);

result.doStuffHere();

return result;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值