我正在尝试转换nisNetgroupTriple字符串,这种格式可以是这种格式:
(host,user,domain)
(,user,)
(host,,)
(host,user,)
(,,domain)
进入如下所示的NetgroupTriple对象:
public class NetgroupTriple {
private String hostname;
private String username;
private String domainName;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
}
我有这个功能,但我希望有一种更清洁的方式使用流。
public static NetgroupTriple fromString(String member) {
NetgroupTriple triple = new NetgroupTriple();
String[] split = member.split(",");
if(split.length != 3)
throw new Exception("bad");
if(!split[0].equals("("))
triple.setHostname(split[0].replace("(",""));
if(!split[1].isEmpty())
triple.setUsername(split[1]);
if(!split[2].equals(")"))
triple.setDomainName(split[2].replace(")",""));
return triple;
}
有谁知道更清洁的方法来实现这个目标?
答案 0 :(得分:1)
如果你知道总是有封装括号,你可以从头开始删除它们
String[] split = member.substring(1, member.length() - 1).split(",");
然后,由于显示传入member
的顺序始终是("主机","用户","域")然后您可以做到
NetgroupTriple triple = new NetgroupTriple(split[0], split[1], split[2]);
所以你的fromString()
看起来像是
public static NetgroupTriple fromString(String member) {
String[] split = member.substring(1, member.length() - 1).split(",");
if(split.length != 3)
throw new Exception("bad");
NetgroupTriple triple = new NetgroupTriple(split[0], split[1], split[2]);
return triple;
}
这将允许您的NetgroupTriple
成为immutable
public class NetgroupTriple {
private String hostname;
private String username;
private String domainName;
public NetgroupTriple(String host, String user, String domain) {
hostname = host;
username = user;
domainName = domain;
}
public String getHostname() {
return hostname;
}
public String getUsername() {
return username;
}
public String getDomainName() {
return domainName;
}
}
答案 1 :(得分:0)
我猜这有效:
public NetgroupTriple(String hostname, String username, String domainName){
this.hostname = hostname;
this.username = username;
this.domainName = domainName;
}
然后解析:
public static NetgroupTriple fromString(String member) {
String[] split = member.split(",");
if(split.length != 3)
throw new Exception(String.format("Could not convert member to NetgroupTriple: %s", member));
return new NetgroupTriple(
split[0].equals("(") ? null : split[0].replace("(",""),
split[1].equals("") ? null : split[1],
split[2].equals(")") ? null: split[2].replace(")",""));
}
仍然没有像我希望的那样优雅。