Java Convert Object Dynamic to Entity

11,939

You could try like this, using reflection to retrieve the declared fields of each Entity object:

 public class CastingTest {

    public static void cast(Object o) throws IllegalArgumentException, IllegalAccessException{
        Class<? extends Object> clazz = o.getClass();
        //clazz.cast(o);
        System.out.println(clazz.getName() + " >> " + clazz.getDeclaredFields().length);
        for(Field f: clazz.getDeclaredFields()){
            f.setAccessible(true);
            System.out.println( f.getName()  + "=" + f.get(o));
        }
    }

    public static void main(String args[]) throws IllegalArgumentException, IllegalAccessException{
        CastingTest.cast(new ClassA("A","B",1));
        CastingTest.cast(new ClassB("A","B",2.25));
    }
}

Testing models. ClassA:

public class ClassA {

    private String a;

    private String b;

    private int c;

    /**
     * @param a
     * @param b
     * @param c
     */
    public ClassA(String a, String b, int c) {
        super();
        this.a = a;
        this.b = b;
        this.c = c;
    }

}

Testing models. ClassB:

public class ClassB {

    private String varA;

    private String varC;

    private double value;

    /**
     * @param varA
     * @param varC
     * @param value
     */
    public ClassB(String varA, String varC, double value) {
        super();
        this.varA = varA;
        this.varC = varC;
        this.value = value;
    }

}

And the output:

com.test.ClassA >> 3
a=A
b=B
c=1
com.test.ClassB >> 3
varA=A
varC=B
value=2.25
Share:
11,939
TheNewby
Author by

TheNewby

Updated on June 04, 2022

Comments

  • TheNewby
    TheNewby about 2 years

    I've created a function which requires a Parameter of type Object.

    public void myFunction(Object obj){
    
    }
    

    Now I have 20 different Entities so the given Object Parameter can be of the type of this 20 entities. I'm searching for a way to cast this Object in the right Entity-type and get all values of it.

    Right now I get the right type with this but I don't know how to cast it to this type and the fields are always 0.

    System.out.println("Class: " + obj.getClass());//Gives me the right type
    System.out.println("Field: " + obj.getClass().getFields().length);//Length is always 0
    
  • TheNewby
    TheNewby over 7 years
    I had this solution too but searching for something dynamic. So I Need to create a if / else if construct fo all of my 20 Entities
  • Hexaholic
    Hexaholic over 7 years
    @TheNewby Maybe Java generics are what you are looking for?
  • TheNewby
    TheNewby over 7 years
    Thanks alot! That's what I was looking for