jeudi 10 décembre 2020

Java Generics - Copy values from sibling class

Is possible to do this in Java?

public class serviceClass<T extends BaseClass, D extends BaseClass> {

    private T copyPropertiesValues(D item) {

        BaseClass item2 =  item.getClass().getDeclaredConstructor().newInstance();
        BeanUtils.copyProperties(item, item2);

        T newItem = (T) item2;

        //newItem is an instance of D instead of T

    }

}

The only way that I found to do this is by going to the "T" class and creating a constructor that takes "D" as parameter.

But I will create a lot of other classes that inherits from BaseClass, and I will need to do this one by one, "repeating" the code.

Is there an easier way to do this?

Thank you.





Aucun commentaire:

Enregistrer un commentaire