【问题标题】:Reflection - How to set values for the POJO Class whose instance is created using reflection反射 - 如何为使用反射创建实例的 POJO 类设置值
【发布时间】:2013-04-24 10:25:16
【问题描述】:

我使用反射为我的 pojo 类创建了一个实例,如下所示:

package com.hexgen.tools;

public class Foo {

    public static void main(String[] args) {
        Class c = null;
        try {
            c = Class.forName("com.hexgen.ro.request.CreateRequisitionRO");
            Object o = c.newInstance();
            System.out.println(o.toString());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }   catch (IllegalAccessException iae) {
            iae.printStackTrace();
        } catch (InstantiationException ie) {
            ie.printStackTrace();
        }  
    }
}

当我打印时,我得到了以下字符串:

com.hexgen.ro.request.CreateRequisitionRO@95c7850[transSrlNo=<null>,transCode=<null>,inflowOutflow=<null>,transDate=<null>,tradeDate=<null>,tradeDateUpto=<null>,tradeTime=<null>,investCategory=<null>,custodian=<null>,holdType=<null>,securityType=<null>,security=<null>,assetClass=<null>,issuer=<null>,fundManager=<null>,marketType=<null>,tradePriceType=<null>,requisitionType=<null>,priceFrom=<null>,priceTo=<null>,marketPrice=<null>,averagePrice=<null>,quantity=<null>,price=<null>,grossAmtTcy=<null>,exchRate=<null>,grossAmtPcy=<null>,grossIntTcy=<null>,grossIntPcy=<null>,netAmountTcy=<null>,netAmountPcy=<null>,acquCostTcy=<null>,acquCostPcy=<null>,yieldType=<null>,purchaseYield=<null>,marketYield=<null>,ytm=<null>,mduration=<null>,currPerNav=<null>,desiredPerNav=<null>,currHolding=<null>,noofDays=<null>,realGlPcy=<null>,realGlTcy=<null>,nowLater=<null>,isAllocable=false,acquCostReval=<null>,acquCostHisTcy=<null>,acquCostHisPcy=<null>,exIntTcy=<null>,exIntPcy=<null>,accrIntReval=<null>,accrIntTcy=<null>,accrIntPcy=<null>,grossAodTcy=<null>,grossAodPcy=<null>,grossAodReval=<null>,bankAccAmtAcy=<null>,bankAccAmtPcy=<null>,taxAmountTcy=<null>,unrelAmortTcy=<null>,unrelAmortPcy=<null>,unrelGlTcy=<null>,unrelGlPcy=<null>,realGlHisTcy=<null>,realGlHisPcy=<null>,tradeFeesTcy=<null>,tradeFeesPcy=<null>,investReason=<null>,settleDate=<null>,stkSettleDate=<null>,custodianN=<null>,portfolio=<null>,userId=<null>]

实际上所有值都设置为空,我想为类中可用的设置器设置值。因为可以随时更改设置器名称,所以我计划动态设置值,这样就不会发生静态值设置。

是否可以为新创建的实例动态设置值?就像创建一些枚举并在枚举中有一些默认值,如果它是字符串,则设置一些默认值,如果 int 设置一些默认值,像这样。

how to do this also i created a object which is not a array if i want to create array of objects using reflection how to go about it?

请帮助我找出并解决这些问题..

【问题讨论】:

    标签: java reflection instances


    【解决方案1】:

    根据定义,POJO 没有标准制定者。我怀疑你的意思是 JavaBean。

    要使用 JavaBean 的 setter,最简单的方法是使用 Introspector

    public class Main {
        public static void main(String... ignored) throws Exception {
            SimpleBean sb = new SimpleBean();
    
            BeanInfo info = Introspector.getBeanInfo(SimpleBean.class);
            System.out.println("Calling setters");
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                if (pd.getWriteMethod() == null) continue;
                System.out.println("\tSetting " + pd.getName());
                pd.getWriteMethod().invoke(sb, "Set now");
            }
            System.out.println("Reading the getters");
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                System.out.println("\t" + pd.getName() + " = " + pd.getReadMethod().invoke(sb));
            }
        }
    
    
        public static class SimpleBean {
            String text;
            String words;
    
            public String getText() {
                return text;
            }
    
            public void setText(String text) {
                this.text = text;
            }
    
            public String getWords() {
                return words;
            }
    
            public void setWords(String words) {
                this.words = words;
            }
        }
    }
    

    打印

    Calling setters
        Setting text
        Setting words
    Reading the getters
        class = class Main$SimpleBean
        text = Set now
        words = Set now
    

    【讨论】:

      【解决方案2】:

      你可以使用类对象定义的字段:

      Field f  = c.getFields()[0]; //or getField("...")
      f.set(o, "new value");
      

      编辑:如果你只想使用 setter:

      for(Method m : c.getMethods())
        if (m.getName().startsWith("set") && m.getParameterTypes().length == 1)
           m.invoke(o, "myValue");
      

      【讨论】:

      • 谢谢 wrm,我的情况是我正在尝试为类创建实例并设置可用属性的值。是否可以找到属性类型并相应地设置值,例如为每种类型设置默认值的枚举并设置它们。还如何使用反射创建对象数组?请不要误会并帮助我
      • 这个`m.getParameterTypes().length == 1`是什么意思?
      • 保证这个方法只接受1个参数而不是更少或更多
      • 感谢 wrm 如果 setter 方法采用其他类型,如 int 或 date 或其他类型。我该怎么做,上面的例子假设它是字符串并设置值是我正确的?
      • 嗯,你可以调用Field.getType,根据字段的类型进行操作。请参阅docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html 了解更多信息
      猜你喜欢
      • 2022-01-09
      • 2016-04-16
      • 1970-01-01
      • 2011-09-12
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多