【问题标题】:Iterate over Two Class with constants and load their fields into a HashMap使用常量迭代两个类并将它们的字段加载到 HashMap
【发布时间】:2016-05-27 17:30:39
【问题描述】:

我有两个带有常量的 java 类,例如:

public class FirstClass {

 public static final String STRING_A = "STRING_A";
 public static final String STRING_B = "STRING_B";
 public static final String STRING_C = "STRING_C";
    ...
}


public class SecondClass {

 public static final String STRING_AA = "STRING_AA";
 public static final String STRING_BA = "STRING_BA";
 public static final String STRING_CA = "STRING_CA";
    ...
}

现在,我想将这些常量加载到一个, Map classPropertyMap = new HashMap(); 这样的话,这个map的Key必须是FirstClass的常量,对应的value必须是SecondClass的常量。 p>

如果只是一个类,我可以使用反射来加载字段,既然常量来自两个类,那怎么办?

最后加载地图后,地图的内容一定是这样的:

第一个元素:键和值是

第二个元素:键和值是

第三个元素:键和值是

【问题讨论】:

  • 您仍然可以使用反射并尝试映射字段,但主要问题是:为什么?你想达到什么目标?这些常量首先是做什么用的?地图的含义是什么?
  • 两个常量类是:第一个包含我声明的属性,第二个包含来自第三方库的属性。我想要一张地图,以便我保持属性同步,即最新的属性。
  • 仍然很难弄清楚实际问题是什么。但是你为什么不只使用一个枚举来表示每个值都包含属性名称的映射呢?或者,如果您不想使用枚举,那么为什么不手动填写地图呢? 3rd 方库中的属性常量无论如何都不应更改,否则您也可能会遇到自动映射问题。
  • 第一个类使用带有字符串字段的枚举怎么样?然后,您可以调用 values() 来获取第一类的所有值。那应该摆脱很多反思。如果我们对您的工作有更多了解,我怀疑我们可以找到更好的解决方案。
  • STRING_A 映射到STRING_AA 的规则是什么?是上课的顺序吗?如果是这样,您没有其他机会,请自己进行映射,因为不能保证在 ByteCode 中的顺序保持不变。

标签: java hashmap


【解决方案1】:

我认为如果您真的需要它,最可靠的方法是将属性显式地放到地图中。

我的意思是map.put(FirstClass.STRING_A, SecondClass.STRING_AA);等等。

如果您使用反射,您将依赖于属性,并且它们的声明顺序永远不会改变。如果库中引入了一些新属性,它可能会破坏您的代码。

【讨论】:

    【解决方案2】:

    试试下面的方法,好像可以实现。

    FirstClass first = new FirstClass();
    Field[] fields = first.getClass().getFields();
    
    SecondClass second = new SecondClass();
    Field[] fields1 = second.getClass().getFields();
    

    【讨论】:

      【解决方案3】:

      试试这个:

      FirstClass first  = new FirstClass();    
      String[] firstStrings = first.getStrings();
      //Makes a String array, and fills it with the strings from the first class.
      
      SecondClass second  = new SecondClass();    
      String[] secondStrings = second.getStrings();    
      //Makes a String array, and fills it with the strings from the second class.
      
      HashMap<String, String> classPropertyMap = new HashMap<String, String>();
      int i = 0;
      
      //Now put strings with the same index number from both arrays into the 
      //HashMap
      
      while(i <= firstStrings.length()){
          classPropertyMap.put(firstStrings.get(i), secondStrings.get(i);
          i++;
      }
      

      希望有效!

      【讨论】:

        猜你喜欢
        • 2012-08-03
        • 1970-01-01
        • 2019-07-24
        • 2011-06-11
        • 2015-12-25
        • 2016-11-27
        • 2016-05-23
        • 2018-12-06
        • 1970-01-01
        相关资源
        最近更新 更多