我正在尝试创建一个新对象并使用以下命令传递的参数对其进行初始化:
java -jar JAR-FILE.jar store Information.dat ClientName“地址”城市国家家庭电话办公电话手机
其中 ClientName
是客户的名称,"Address"
包含客户的地址等。客户可以拥有 HomePhone
或办公电话
或手机
或所有这些甚至更多的电话号码。
这是我尝试使用参数初始化它的类:
private static void SaveClient(String[] args) throws Exception
{
Client SaveClient = new Client(...);
....
out.writeObject(SaveClient);
out.close();
}
这是Client
构造函数:
public class Client{
private String ClientName;
private Address address;
private List<String> PhoneNumbers;
public Client() {
this.PhoneNumbers = new ArrayList<String>();
}
public Client(String ClientName, Address address) {
this();
this.name = ClientName;
this.address = address;
}
public void AddPhoneNumber(String number) {
this.PhoneNumbers.add(number);
}
....
}
但我不知道如何使用传递参数来初始化它。我们可以假设该信息是有效的,而且我不想对“Client”构造函数进行任何更改,只需修改 SaveClient
最佳答案
首先,您需要确定提供的参数数量是否满足您的预期需求...
// This assumes that address, city, country, home phone,
// office and cell phone are optional
if (args.length >= 3) {...
或者
// This assumes that all the values are required...
if (args.length >= 9) {...
如果这两种情况都不正确(根据您的需要),那么您应该显示某种错误消息并可能退出...
然后您需要从 args
中提取值...
// This assumes that some of the arguments are optional...
String clientName = args[2];
String address = args.length > 3 ? args[3] : null;
String city = args.length > 4 ? args[4] : null;
String country = args.length > 5 ? args[5] : null;
String homePhone = args.length > 6 ? args[6] : null;
String officePhone = args.length > 7 ? args[7] : null;
String cellPhone = args.length > 8 ? args[8] : null;
或者
// This assumes that all the parameters are mandatory
String clientName = args[2];
String address = args[3];
String city = args[4];
String country = args[5];
String homePhone = args[6];
String officePhone = args[7];
String cellPhone = args[8];
然后创建您的Client
对象...
Client client = new Client(
clientName,
address,
city,
country,
homePhone,
officePhone,
cellPhone);
这当然意味着您的 Client
对象将需要一个能够接受您提供的信息的构造函数。您的示例 Client
将无法工作,除了它有一个无效的 Person
构造函数这一事实之外,它无法接受所有这些信息......
public class Client{
private String ClientName;
private Address address;
private List<String> PhoneNumbers;
public Client() {
this.PhoneNumbers = new ArrayList<String>();
}
public Client(String clientName, String address, String city, String country, String homePhone, String officePhone, String cellPhone) {
this();
ClientName = clientName;
address = new Address(...); // No idea of the parameters for this...
AddPhoneNumber(homePhone);
AddPhoneNumber(officePhone);
AddPhoneNumber(cellPhone);
}
例如...
关于java - 在Java中创建一个对象并通过传递参数来初始化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22238112/