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

  • Home
  • SEARCH
  • 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 7024981
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T23:54:51+00:00 2026-05-27T23:54:51+00:00

Is this possible? I am creating a an object from a JSON string with

  • 0

Is this possible? I am creating a an object from a JSON string with this code:

String obj = new Gson().toJson(jsonArray.getJSONObject(i));
String className = getClassName(jsonArray.getJSONObject(i));

Class targetClass = null;
try {
    targetClass = Class.forName(className);
} catch (ClassNotFoundException e) {
                e.printStackTrace();
}

//Create Object
Object data = new Gson().fromJson(obj, targetClass);

I then do some database stuff, get a return key value and I want to set that key on the bean object using its setId() setter, but I don’t want to have to cast the specific type of object to the generic object because that would require my repeating the exact same code many times just to cast the object.

key = contactsListDAO.manageDataObj(data, sql, true);
((PhoneNumber) data).setId(key);

Can I use some sort of if statement to check if the object contains an id property and then set the id on the generic object without having to cast?

  • 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-27T23:54:52+00:00Added an answer on May 27, 2026 at 11:54 pm

    reflection can do that but I think maybe here you should do something else.
    Write a utility function

    public static <T> T fromJson(String json, Class<T> clzz)
    {
    return (T) new Gson().fromJson(obj, targetClass);
    }
    

    and then you can call it like so

    PhoneNumber data = fromJson(obj, PhoneNumber.class); 
    

    no more conversion.

    EDIT : if using “Object” is a constraint you can use reflection

    public void  setIdOnObject(Object obj, Object id)
        {
            try{
             Method m =  obj.getClass().getMethod("setId",id.getClass());
                m.invoke(obj, id );
    
            }catch(NoSuchMethodException  e){ return false; } catch (InvocationTargetException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (IllegalAccessException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    

    Here is a working example I have, just copy-paste-run.

    import java.lang.reflect.InvocationTargetException;
    public class Reflection
    {
    
        public static void main( String[] args )
        {
            MyParent p = new MyParent();
            setParentKey( p, "parentKey" );
    
            MyObj o = new MyObj();
            setParentKey( o, "myParentKey" );
            setMyKey( o, "myKey" );
    
            System.out.println( "p = " + p );
            System.out.println( "o = " + o );
    
        }
    
    
    
        public static void invokeMethod( Object p, Object k, String methodName )
        {
            try
            {
                p.getClass().getMethod( methodName, k.getClass() ).invoke( p, k );
            }
            catch ( NoSuchMethodException e )
            {
                e.printStackTrace();
            }
            catch ( InvocationTargetException e )
            {
                e.printStackTrace();
            }
            catch ( IllegalAccessException e )
            {
                e.printStackTrace();
            }
        }
    
        public static void setParentKey( Object p, Object k )
        {
               invokeMethod( p,k,"setParentKey" );
        }
    
        public static void setMyKey( Object p, Object k )
        {
            invokeMethod( p,k,"setMyKey" );
        }
    
        public static class MyParent
        {
            private Object parentKey;
            public void setParentKey( String k )
            {
                parentKey = k;
            }
    
            @Override
            public String toString()
            {
                return "MyParent{" +
                               "parentKey=" + parentKey +
                               '}';
            }
        }
    
        public static class MyObj extends MyParent
        {
            private Object myKey;
            public void setMyKey( String k )
            {
                myKey = k;
            }
    
            @Override
            public String toString()
            {
                return "MyObj{" +
                               "myKey=" + myKey +
                               "} " + super.toString();
            }
        }
    }
    

    And the expected output is :

    p = MyParent{parentKey=parentKey}
    o = MyObj{myKey=myKey} MyParent{parentKey=myParentKey}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is this possible? I am creating a single base factory function to drive factories
I want to do this web application I am creating in the best possible
Is this possible? I've followed the instructions from here ( http://www.jetbrains.net/confluence/display/TCD4/Setting+up+an+External+Database#SettingupanExternalDatabase-MicrosoftSQLServer2005 ) but I
Is this possible? example: $('a.change').click(function(){ //code to change p tag to h5 tag });
Here's the question first: Is this possible? I'm taking my inspiration from Joe Wrobel's
I am starting with this object, public class myTO { private String id; private
I am creating a remotable object using WCF. This is a snipped of how
Is it possible to use PHP's SimpleXML functions to create an XML object from
Given this code, how do I get the values from the checkbox- and textpreference
Possible Duplicate: How to pass object from one activity to another in Android While

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.