Return new instance of child class from parent class in JAVA

107
June 14, 2022, at 7:50 PM

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

    }
}
Answer 1

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.

Rent Charter Buses Company
READ ALSO
Create collection of cartesian product of two (and more) lists with Java Lambda

Create collection of cartesian product of two (and more) lists with Java Lambda

I'm able to easily achieve this in Scala with something like:

93
removeUniqueElementsWithEqualHashesDecrementsSize test nor workin with hastable

removeUniqueElementsWithEqualHashesDecrementsSize test nor workin with hastable

I have one test in this testclass that is not going throughI have implemented how I think it should be written, but I get a message :

89
Conditional code based on Build/flavor - Identical to C# #if DEBUG

Conditional code based on Build/flavor - Identical to C# #if DEBUG

In C# there is a way to include/exclude parts of the code based on build type

85