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

563 Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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

0
On

Java is not meant for changing classes or creating new classes at runtime.

It is possible with a lot of effort, like generating java bytecode on the fly using a bytecode library like BCEL(http://commons.apache.org/proper/commons-bcel/) or even generate .java files and run javac to generate bytecode.

You could simply use a hash map like Map<String,Object> that "simulates" an object that can receive arbitrary fields. If you really need totally configurable classes, I would go this way. Of course, you would not have nice getters and setters for each property.

But why would you need nice setters / a nice class anyway? As the structure of the class is determined at runtime, you can write no code that depends on this class, as you do not know how it will look like.