Return new instance of child class from parent class in JAVA

Viewed 280

I have been working on ORM.wanted a feature where any child class which extends DbModel class will be able to use all the static methods within the parent class. However, most static methods return instance of Parent class.
Is there any way whereby which child class will get an instance of itself from the methods?


DbModel.java -> access the db

public class DbModel {

     public DbModel(String tableName)
     {
     }

    public static DbModel findById(String tableName , String id){
        //some logic ....
        return new DbModel(tableName);
    }

    public static DbModel findByValue(String tableName ,String value){
        //some logic ....
        return new DbModel(tableName);
    }
    
}

Users -> users class which contains users logic. Similarly, there will be many classes.

public class Users extends DbModel {


    public Users() {
        super("users");
    }

    //some method
    public String getFullName(){
        //some logic
        return "fullname";
    }


}

Test.java -> test class

public class Test {

    public static void main(String[] args) {

        //--> ERROR : DbModel cannot be cast to Users
        Users users = Users.findById("","");
        //what I want : Users.findById should return Users type not DbModel



    }

}
1 Answers

You can add a param that lets you specify the type you want to be returned to bind the generics, then just invoke the appropriate constructor of that type.

public class DbModel {

    public DbModel(String tableName) { ...}

    public static <T extends DbModel> T findById(
            String tableName, String id, Class<T> type
    ) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

        //stuff

        return type.getConstructor(String.class).newInstance(tableName);
    }

}

The amount of checked exceptions here should tell you that this is not the safest or most maintainable way to code this. You should look into using the https://en.wikipedia.org/wiki/Abstract_factory_pattern instead.

Related