Search code examples
javastatic-binding

Get around early binding of static methods in java


I have a AbstractBaseRepository. All my Repositories extends from this class. I created another class RepositoryFactory to create any instance of Repository. Due to early binding of static method, I am facing problem.

public abstract class AbstractBaseRepository {
    public static <T extends AbstractBaseRepository> T getNewInstance(EntityManagerFactory entityManagerFactory) {
        throw new RuntimeException("Override and provide valid initialization");
    }
    ...
}

public class RepositoryFactory {
    public static <T extends AbstractBaseRepository>  T getRepository(Class<T> cls) {       
        return T.getNewInstance(entityManagerFactory);
    }
    ...
}

an example subclass

public class DeviceModelRepo extends AbstractBaseRepository {

    public static DeviceModelRepo getNewInstance(EntityManagerFactory entityManagerFactory) {
        return new DeviceModelRepo(entityManagerFactory);
    }
    ...
}

Whenever I call getRepository() with a valid subclass of AbstractBaseRepository, runtime exception is thrown. This is due to early binding of static methods. During compile time, getNewInstance gets bound with AbstractBaseRepository rather than at runtime with actual type of the class. Any good workarounds?


Solution

  • My first suggestion is using Spring. It is very easy to get a list of all beans created with a certain interface.

    Also, if you think of your Repository instances as a type of "plug-in" you might see how Java's ServiceLoader class can help.

    Also, another approach is to use a switch statement in the factory and create the instances for each case rather than using static methods on the Repository subclasses.

    Finally, I don't recommend reflection solutions but there are ways to load the class based on its name and reflectively creating a new instance.

    But overriding static methods is not possible.