我有一個具有各種屬性的類,我想圍繞它們編寫一個包裝方法,以便更容易地環繞它們。返回一個集合或單個值的方法
一些屬性返回值的收集,有的單值。我正在尋找最佳方法。
我的第一種方法是讓包裝方法返回任何屬性getters返回。
public class Test {
public Object getValue(String propName) {
if ("attr1".equals(propName)) return getAttribute1();
else if ("attr2".equals(propName)) return getAttribute2();
else return null;
}
public List<String> getAttribute1() {
return Arrays.asList("Hello","World");
}
public String getAttribute2() {
return "Goodbye";
}
public static void main(String[] args) {
final Test test=new Test();
Stream.of("attr1","attr2")
.forEach(p-> {
Object o=test.getValue(p);
if (o instanceof Collection) {
((Collection) o).forEach(v->System.out.println(v));
}
else {
System.out.println(o);
}
});
}
}
壞點這種方法是調用者測試自己的結果是否是一個集合與否。
調用方無縫的其他方法是始終返回一個集合,即。包裝函數將單個值包裝到Collection中。這裏有一個HashSet,但我們可以想象一個adhoc,最少1個元素列表。
public class TestAlt {
public Collection getValue(String propName) {
if ("attr1".equals(propName))
return getAttribute1();
else if ("attr2".equals(propName)) {
Set s = new HashSet();
s.add(getAttribute2());
return s;
}
else
return null;
}
public List<String> getAttribute1() {
return Arrays.asList("Hello", "World");
}
public String getAttribute2() {
return "Goodbye";
}
public static void main(String[] args) {
final TestAlt test = new TestAlt();
Stream.of("attr1", "attr2")
.forEach(p -> {
test.getValue(p).forEach(v -> System.out.println(v));
});
}
性能方面,設計方面......您對這些方法有什麼看法?你有更好的想法嗎?
Guess =你可以有一個只有一個項目的集合嗎? – Marichyasana
你是_just_試圖打印所有的值?沒有其他用途?此外,該類型將始終是「列表」和「字符串」之一嗎?會有其他類型像'int'嗎? –
Sweeper
@Marichyasana只有一個項目的集合很容易寫入 – lvr123