javaanonymous-classdynamic-class-creation

Change class structure at runtime or get it into a anonymous class


I have

class A
{
String a;
String b;
//..getters, setters
}

Now I have ArrayList<? extends Object> resultData holding objects of class A and some other classes. Basically I need this list 'resultData' to generate a Json file in some other API.

Now my question is while adding the class A objects to the list & some condition(X) is true I need a modified class A object (or any other anonymous class object) like:

class A
{
String a;
//..getters, setters
}

that is one particular object of class A shouldn't have field String b (before criticising, I'm doing this because I need such modified object for my particular JSon format & I don't want to define a new class definition that is used only once)

my last option is to make anonymous class like this: (& then add it to my List)

Object ob = new Object{
String b;
//..getters, setters
}

Also pls. suggest any other method of creating anonymous class with required structure.


Solution

  • if i'm getting you correctly, you need to get rid off field for serialization, to json format, if im right, then make your field transient

    other solution is to make super class with field which you want to serialize, and make A to extend it

    but modifying class on fly, it is not right way to go