嘿,我已将类 Prop 定义为
`
class prop{
String name;
String address;
String city;
public void String getValue(String str){
String res=null;
if(str.equals("name"))
res="john";
if(str.equals("city"))
res="london";
return res;
}`
我已经定义了这样的getter类,是否可以通过其他方式定义通用的getter方法。
有人告诉我使用枚举类,但我不明白枚举在这里有何用处。
函数 getValue(String str) 中的参数是一个 String,因为它正在被其他类调用。
最佳答案
你可以尝试这样的事情:
class Prop{
public enum Properties {
Name,
Address,
City
}
Map<Properties, String> propertyMap;
public Prop() {
this.propertyMap = new HashMap<Properties, String>();
}
public void String setValue(Properties prop, String value){
this.propertyMap.put(prop, value);
}
public void String getValue(Properties prop){
return this.propertyMap(prop);
}
}
增加值(value):
Prop prop = new Prop();
...
prop.setValue(prop.Properties.Name, "Bob");
...
String name = prop.getValue(prop.Properties.Name); //Should be Bob, assuming it did not change.
编辑: 根据您的查询,您可以这样做:
class Prop{
Map<String, String> propertyMap;
public Prop() {
this.propertyMap = new HashMap<String, String>();
}
public void String setValue(String prop, String value){
this.propertyMap.put(prop, value);
}
public void String getValue(String prop){
return this.propertyMap(prop);
}
}
这种方法的问题是,无论谁调用您的代码,都必须猜测或者对调用您的代码有某种先验知识。通过枚举,您可以预先提供 map 可以具有哪些属性。
关于java - java中类中的通用getter方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28673653/