Reflection - How to set values for the POJO Class whose instance is created using reflection

StackOverflow https://stackoverflow.com/questions/16189566

  •  11-04-2022
  •  | 
  •  

Вопрос

i have created a instance for my pojo class like the following using reflection :

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();
        }  
    }
}

when i printed i got the following string :

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>]

literally all the values are set to null, i would like to set the values for the setters available in the class. since the setters name can be changed at any time i plan to set values dynamically so that there is no static value setting happens.

is it possible to set the values dynamically for the newly created instance? Like creating some enums and have some default values in enum like if it is string set some default values if int set some default values like so.

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?

kindly help me to figure out and fix these..

Это было полезно?

Решение

POJO's don't have standard setters by definition. I suspect you meant JavaBean.

To use setters of a JavaBean, the simplest approach is to use the 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;
        }
    }
}

prints

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

Другие советы

you can use the fields defined by the class object:

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

edit: if you want to only use setters:

for(Method m : c.getMethods())
  if (m.getName().startsWith("set") && m.getParameterTypes().length == 1)
     m.invoke(o, "myValue");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top