我需要在运行时(通过扫描仪类)
创建任一数据类型的变量这就是我的作业所要求的
"销售安排可以是发售价格或拍卖日期"
这是我创建的,但不确定它是否正确..
public class SellingArrangement {
private Object dateOrPrice;
public SellingArrangement()
{
}
public void setDateOrPrice(String price)
{
dateOrPrice = new Object();
dateOrPrice = price;
}
public void setDateOrPrice(Double price)
{
dateOrPrice = new Object();
dateOrPrice = price;
}
答案 0 :(得分:3)
之前我做过类似的事情(当API可能返回JSON或XML时)
但是,这里有两组选择 - 输入可以是String或Double,输入可以表示日期或价格。
我不是使用Object,而是创建两个单独的字段,并使用两个单独的构造函数填充正确的字段。
public class SellingArrangement {
private Date date;
private Price price;
public SellingArrangement(String input)
{
if ( // String is a price ) {
this.price = new Price(input);
}
if ( // String is a date ) {
this.date = new Date(input)
}
}
public SellingArrangement(Double input)
{
if ( // Double is a price ) {
this.price = new Price(input);
}
if ( // Double is a date ) {
this.date = new Date(input)
}
}
}
当然,我假设您可以找出一些方法来验证您输入的String或Double是一个日期还是价格,并且您拥有的构造函数将为每种类型采用String / Double。把它当作伪代码......
然而正如其他人在评论中提到的,如果你没有 用一个类做这个,那么最好完全使用另一种方法......