mercredi 18 mars 2020

Way of invoking setter methods using reflection based on getters of another Object

I have 2 objects which are related

One of them is of class Attribute, the other one is something like controller of that called AddAttributeActionHandler

The Attribute object has a lot of fields in it which I need to set in AddAttributeActionHandler Both classes have getters and setters some of them are equal.

Basically what I what is to copy every available getter from the class Attribute and invoke according setter method on the class AddAttributeActionHandler

In other words I can execute the following (you can call it "manual" setting)

Attribute attributeObj = getAttributeObj();

String codeFromAttrObj = attributeObj.getCode();
String titleFromAttrObj = attributeObj.getTitle();


AddAttributeAction action = AddAttributeAction.create();

action.setCode(codeFromAttrObj);
action.setTitle(titleFromAttrObj);

The problem is that there are just like 50+ fields. I'd like it to be fully automatic.

So, I've found the following code for getting every available public getter for the object Attribute

for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(attributeObj.getClass()).getPropertyDescriptors())
    {
        if(propertyDescriptor.getReadMethod().toString() != "null") 
        {
            String getterMethodName = propertyDescriptor.getReadMethod().toString();
            String getterMethodValue = propertyDescriptor.getReadMethod().invoke(attributeObj).toString());
        }      
    }

The code above gets every getter available in the object and prints its value.

Now I need to find out whether there's a corresponding setter method in the object of the class AddAttributeActionHandler and set the property which I got from the getter in the Attribute object.

Is it possible?

If so, please provide any clues.

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire