mercredi 9 septembre 2020

Java : Getting the Values from the Attribute names (attributes name and type unkown at runtime)

I have two objects - output ( having 20 fields or attributes ) and an object o with some of these fields (varying from 1 - 5) .

I want to compare the values of these all 5 fields of object o with thier values in output object.

Say output object has attributes a to z. and Object o has attributes a to c , so I want to compare the value of output.a,output.b and output.c with o.a,o.b and o.c

Note I dont know if o.a,o.b and o.c exists or not but I am retrieving their attributes from the fields dynamically:

Below is the code. I have marked with the line what is working and what is not working . I dont know how to type cast it as I dont know the attribute names .

  private void CompareObjects(Output output,Object o) throws IllegalAccessException, NoSuchFieldException {

        Class<?>  r = o.getClass();
        Field[] fields = respclass.getDeclaredFields();
        for (Field field : fields) {

          String fname =   field.getType().getSimpleName();
          print((field.getName())output.getClass().getDeclaredField(fname));// NOT Working error line, not able to typecast it with the field.getName()
//          print(field.getType())output.getClass().getDeclaredField(fname)); // NOT Working

        }




Aucun commentaire:

Enregistrer un commentaire