簡體   English   中英

使用反射設置值時面臨的問題

[英]problem faced while setting value using reflection

我使用反射將字段的值從類A的對象復制到類B的對象。但是A中的方法返回Number,其中B中的setter需要Long。 有什么通用的方法可以設置值。 截至目前,正如我所料,我得到了invalidArgumentException:參數類型不匹配

class a
{
    Number value1;
    Number value2;
    public Number getValue1(){return value1;}
    public Number getValue2(){return value2;}

}

class b
{
    Double value1;
    Long   value2;
    public void setValue1(Double value){this.value1 = value;}
    public void setValue2(Long value){this.value2 = value;}

}

不確定我的問題是否不清楚。

你可以做到

b.setValue2(a.getValue2().longValue());

但是,如果a.value2實際上不是整數(例如,它是帶有小數部分的Double ),則會丟失數據。

相應地

b.setValue1(a.getValue1().doubleValue());

編輯

好的,我想我已經掌握了你的情況。 這是一個骯臟的方式去做你想做的事情。 基本上你需要有一個轉換方法,它會根據所選的類將Number轉換為另一個Number。 該類是從Method本身獲得的。 所以它會是這樣的:

   public static void main(String[] args) throws Exception {
      A a = new A();
      a.setValue1(1.0);
      a.setValue2(5);

      B b = new B();

      Method[] methods = b.getClass().getMethods();
      for ( Method m : methods ) {
         if ( m.getName().equals("setValue2") ) {
            m.invoke(b, transform(a.getValue2(), m.getParameterTypes()[0]));
         }
      }
      System.out.println(b.getValue2());
   }

   private static Number transform(Number n, Class<?> toClass) {
      if ( toClass == Long.class ) {
         return n.longValue();
      } else if ( toClass == Double.class ) {
         return n.doubleValue();
      }
      //instead of this you should handle the other cases exhaustively
      return null;
   }

否則會在上面獲得IllegalArgumentException的原因是因為使用avalue2未被設置為Long ,而是被設置為Integer 它們是不相交的類型。 如果實際上將a.value2設置為Long,則不會出現該錯誤。

您需要進行轉換:

// get the Number 'number'
Long l = new Long(number.longValue());
// store the Long

您可以使用自動裝箱更有效地完成此操作。

您不能以“通用”方式執行此操作,因為Number可能是FloatByte等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM