【问题标题】:How to pass a class-element of an ArrayList type on to a method如何将 ArrayList 类型的类元素传递给方法
【发布时间】:2016-03-01 10:59:43
【问题描述】:

如何将 ArrayList 类型的元素传递给方法?我的天真尝试如下。

public double example( ArrayList<CMyType> list, String type ){

    double out = list.get(0).type // type should be a placeholder for one of the variables which I defined in CMyType
    return out;

}

public class CMyType {
    public double var1;
    public double var2;
}

【问题讨论】:

    标签: java arraylist methods types


    【解决方案1】:

    你在这里尝试做的事情:

    double out = list.get(0).type // type should be a placeholder for one of 
    

    不使用反射是不可能的,像这样:

    public double example( ArrayList<CMyType> list, String type ) {
      CMyClass obj = list.get(0);
      Field field = obj.getClass().getDeclaredField(type);
      Object objOut = field.get(obj);
      // you could check for null just in case here
      double out = (Double) objOut;
      return out;
    }
    

    您还可以考虑将您的 CMyType 类修改为如下所示:

    class CMyType {
      private double var1;
      private double var2;
    
      public double get(String type) {
        if ( type.equals("var1") ) {
          return var1;
        } 
        if ( type.equals("var2") ) {
          return var2;
        }
    
        throw new IllegalArgumentException();
    }
    

    然后像这样从您的代码中调用它:

    public double example( ArrayList<CMyType> list, String type ) {
      CMyClass myobj = list.get(0);
      return myobj.get(type);
    }
    

    更好的解决方案是像这样在CMyType 中使用Map&lt;String, Double&gt;

    class CMyType {
      private Map<String, Double> vars = new HashMap();
    
      public CMyType() {
        vars.put("var1", 0.0);
        vars.put("var2", 0.0);
      }
    
      public double get(String type) {
        Double res = vars.get(type);
        if ( res == null ) throw new IllegalArgumentException();
        return res;
    }
    

    【讨论】:

      【解决方案2】:

      为什么不直接

      public double example( ArrayList<CMyType> list, String type ){
          double out = list.get(0).type // type should be a placeholder for one of the variables which I defined in CMyType
          return out;
      }
      
      public class CMyType {
          public double var1;
          public double var2;
      }
      
      public invocationTest() {
         ArrayList<CMyType> arrayList = new ArrayList<CMyType>(); //or populate it somehow
         return myExample(arrayList.get(0));
      }
      
      public double myExample( CMyType member, String type ){
          double out = member.type;
          return out;
      }
      

      【讨论】:

      • 我认为他想使用type 作为CMyType 字段的字段名称
      • 啊,那他需要用反射来访问String类型的成员。
      猜你喜欢
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多