Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Convert Object Dynamic to Entity

Tags:

java

casting

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
like image 790
TheNewby Avatar asked Apr 12 '26 19:04

TheNewby


1 Answers

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
like image 139
jlumietu Avatar answered Apr 20 '26 04:04

jlumietu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!