java - java中类中的通用getter方法

标签 java enums

嘿,我已将类 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/

相关文章:

c# - 反射 - 带参数调用构造函数

c# - 获取具有不同键的重复值的枚举变量的值

java - Jackson 中的 @XmlPath 模拟是什么?

python - PyCharm 类型提示枚举迭代

java - TCP 连接 - 服务器仅在关闭套接字后发送消息

java - 如何在android工具测试中检查工具栏标题?

java 枚举 : conceptual doubt

postgresql - 列出 Postgres 中特定数据库的所有用户创建的枚举

java - 如何解决java.lang.IllegalStateException?

java - 将时间戳转换为 weekNumber mapReduce