Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7668691
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T15:25:28+00:00 2026-05-31T15:25:28+00:00

I’m using reflection to map getters from one class to setters in another i.e.

  • 0

I’m using reflection to map getters from one class to setters in another i.e. I have form classes used by stuts1 for display mostly text (Strings) and I have pure Java objects used by the back end which holds the values in their specific type. I’ve currently got the mapping working between the getters and setters which was easy but I’m having trouble with the mixed types. I’m using the parameter type from the setter to see what’s expected and so I need to determine the type of the object from the getter and cast it some how to the expected type.

E.g.

HomePageForm  ->   HomePageData 
Name="Alexei" ->   String name; (Maps correctly) 
Age="22"      ->   int age;     (Needs casting from string to int and visa-vera in reverse)

The following is my code so far

/**
     * Map the two given objects by reflecting the methods from the mapTo object and finding its setter methods.  Then 
     * find the corresponding getter method in  the mapFrom class and invoke them to obtain each attribute value.  
     * Finally invoke the setter method for the mapTo class to set the attribute value.  
     * 
     * @param mapFrom The object to map attribute values from
     * @param mapTo   The object to map attribute values to
     */
    private void map(Object mapFrom, Object mapTo) {
        Method [] methods = mapTo.getClass().getMethods();
        for (Method methodTo : methods) {
            if (isSetter(methodTo)) {
                try {
                    //The attribute to map to setter from getter
                    String attName = methodTo.getName().substring(3);

                    //Find the corresponding getter method to retrieve the attribute value from
                    Method methodFrom = mapFrom.getClass().getMethod("get" + attName, new Class<?>[0]);

                    //If the methodFrom is a valid getter, set the attValue
                    if (isGetter(methodFrom)) {
                        //Invoke the getter to get the attribute to set
                        Object attValue = methodFrom.invoke(mapFrom, new Object[0]);

                        Class<?> fromType = attValue.getClass();

                        //Need to cast/parse type here
                        if (fromType != methodTo.getParameterTypes()[0]){
                            //!!Do something to case/parse type!!
                        } //if

                        //Invoke the setter to set the attribute value
                        methodTo.invoke(mapTo, attValue);
                    } //if
                } catch (Exception e) {
                    Logger.getLogger(Constants.APP_LOGGER).fine("Exception in DataFormMappingService.map: "
                                                              + "IllegalArgumentException" + e.getMessage());
                    continue;
                }
            } //if
        } //for
    } //map

Thanks in advance,
Alexei Blue.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T15:25:29+00:00Added an answer on May 31, 2026 at 3:25 pm

    I implemented a better solution in the end:

        /**
         * Map to given objects taking into account the inclusion and exclusion sets.
         * 
         * @param mapFrom The object to map attribute values from
         * @param mapTo   The object to map attribute values to
         */
        private void map(Object mapFrom, Object mapTo)
        {
            setMapFilter(mapFrom, mapTo);
    
            for (Method sMethod : filterMap.keySet())
            {            
                try
                {
                   //Find the corresponding getter method to retrieve the attribute value from
                    Method gMethod = filterMap.get(sMethod);
    
                    //Invoke the getter to get the attribute to set
                    Object attValue = gMethod.invoke(mapFrom, new Object[0]);
    
                    //Get the mapping types and check their compatibility, if incompatible convert attValue type to toType
                    Class<?> fromType = gMethod.getReturnType();
                    Class<?> toType   = sMethod.getParameterTypes()[0];
    
                    if(!toType.isAssignableFrom(fromType) && Objects.isNotNull(attValue))
                    {
                        attValue = parseType(attValue, toType);
                    } //if
    
                    //Invoke the setter to set the attribute value
                    sMethod.invoke(mapTo, attValue);
                }
                catch (IllegalArgumentException e)
                {
                    Logger.getLogger(Constants.APP_LOGGER).fine("Exception in DataFormMappingService.map: "
                                                              + "IllegalArgumentException " + e.getMessage());
                    continue;
                }
                catch (IllegalAccessException e)
                {
                    Logger.getLogger(Constants.APP_LOGGER).fine("Exception in DataFormMappingService.map: "
                                                              + "IllegalAccessException " + e.getMessage());
                    continue;
                }
                catch (InvocationTargetException e)
                {
                    Logger.getLogger(Constants.APP_LOGGER).fine("Exception in DataFormMappingService.map: "
                                                              + "InvocationTargetException " + e.getMessage());
                    continue;
                }
            } //for each
        } //map
    
        /**
         * Refactored method to parse an object, attValue, from it's unknown type to the type expected.
         * 
         * @param attValue The attribute value to parse
         * @param type     The type expected/to convert to
         * @return         The attribute value in the expected type, null otherwise
         */
        private Object parseType(Object attValue, Class<?> type)
        {
            Object newAttValue = null;
    
            if (isLiteral(type))
            {
                newAttValue = attValue.toString();
            }
            else if (isByte(type))
            {
                newAttValue = Byte.valueOf(attValue.toString());
            }
            else if (isInt(type))
            {
                newAttValue = Integer.valueOf(attValue.toString());
            }
            else if (isShort(type))
            {
                newAttValue = Short.valueOf(attValue.toString());
            }
            else if (isLong(type))
            {
                newAttValue = Long.valueOf(attValue.toString());
            }
            else if (isFloat(type))
            {
                newAttValue = Float.valueOf(attValue.toString());
            }
            else if (isDouble(type))
            {
                newAttValue = Double.valueOf(attValue.toString());
            }
            else if (isBoolean(type))
            {
                newAttValue = Boolean.valueOf(attValue.toString());
            } //if-else if*
    
            return newAttValue;
        } //parseType
    

    It’s cleaner than my original solution but essentially when mapping, a filter is built of methods to map which is simply looped through and then mapped. The parse method just checks types and uses the valueOf method on an Object.toString() which works for standard Java types.

    Cheers,

    Alexei Blue.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a text area in my form which accepts all possible characters from
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have thousands of HTML files to process using Groovy/Java and I need to
I'm making a simple page using Google Maps API 3. My first. One marker
I have a bunch of posts stored in text files formatted in yaml/textile (from
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.