mardi 3 octobre 2023

How to use Reflection in Java to dynamically create classes?

Im sorry if this will sound confusing but I will try best. I have a question about dynamically creating classes using reflection.

I have a holding class, that only has member attributes of 'subclasses', all the holding class's attributes are the same subclass type but just have different variable names.

The holding class will receive a json object with attributes like idNo, some text, and an identifier, this identifier will point to the specific subclass that will have its attributes created.

So three parts here

  1. Holding class with attributes of sub classes
  2. JSON Array
  3. HashMap that contains identier to the name of the subclass like

HashMap

    dictionary.put("blue", "two");
    dictionary.put("black", "one");
    dictionary.put("red", "three");
    dictionary.put("green", "four");

Json Array is something like

"[{\"identifier\":\"blue\",\"invoId\":1,\"questNo\":1,\"seqId\":\"1a\","answerText\":1},{\"identifier\":\"red\",\"invoId\":1,\"questNo\":2,\"seqId\":\"2a\",\"answerText\":0},{\"identifier\":\"green\",\"invoId\":1,\"questNo\":3,\"seqId\":\"3a\",\"answerText\":1},{\"identifier\":\"black\",\"invoId\":1,\"questNo\":4,\"seqId\":\"4a\"}.\"answerText\":0]"

As you can see, the JSONARRAY has a colour, the HashMap has a colour to a number, and that number specifies which subclass to construct.

HOLDING CLASS
`public class HoldingClass {
    private SubClass one;
    private SubClass two;
    private SubClass three;
    private SubClass four;`
    



SUBCLASS
'public class SubClass<T> {
    private String identifier;
    private String seqId;
    private int questNo;
    boolean answerText;
    private int invoId = 1;'

The part I cannot figure out, is how to use reflection such that, it points to a specific subclass attribute in the holding class, then construct's that subclass of the specific array element's info.

Any help would be greatly appreciated!





Aucun commentaire:

Enregistrer un commentaire