dimanche 2 juillet 2023

Specifying child method with base class object in Java

I've written below snippet to produce better and reusable code in all of Child classes.

Base Entity :

public class BaseEntity{
     Integer id; 
     //setter getters etc
}

Child Entity :

public class MyChild extends BaseEntity{
    String name;
    //setter getters etc
}

I have many child classes that extends BaseEntity and want to write a method to remove boilerplate code.

Util Class :

public class Util{
    public String getName(BaseEntity base){
        return base != null ? base.getChild().getName() : "";
    } 
}

The problem is base.getChild.name() How to do something like that when child isn't in a composition form ? I've reading about Java Reflection but don't know how to do it in an optimise way in this scenario.. Is there any better option than Reflection ?





Aucun commentaire:

Enregistrer un commentaire