I have interface called RestClientInterface which is implemented by abstract RestClient class, those class is extended by SearchRestClient and IndexRestClient. Both of those classes are singletons. I would like to be able implement in the interface static method getInstance. I decided to use Guava library like suggested here: How can I implement abstract static methods in Java?.
I have implemented two statics methods in interface:
public interface RestClientInterface {
ClassToInstanceMap<RestClientInterface> classToInstanceMap = MutableClassToInstanceMap.create();
static <T extends RestClientInterface> T getInstance(Class<T> type) {
return classToInstanceMap.getInstance(type);
}
static <T extends RestClientInterface> void registerInstance(Class<T> type, T identity) {
classToInstanceMap.putIfAbsent(type, identity);
}
}
And next registered instances in both extending classes:
public class IndexRestClient extends RestClient {
static {
RestClientInterface.registerInstance(IndexRestClient.class, getInstance());
}
/**
* IndexRestClient singleton.
*/
private static IndexRestClient instance = null;
private IndexRestClient() {}
/**
* Return singleton variable of type IndexRestClient.
*
* @return unique instance of IndexRestClient
*/
private static IndexRestClient getInstance() {
if (Objects.equals(instance, null)) {
synchronized (IndexRestClient.class) {
if (Objects.equals(instance, null)) {
instance = new IndexRestClient();
instance.initiateClient();
}
}
}
return instance;
}
}
Next I call this like that:
IndexRestClient restClient = RestClientInterface.getInstance(IndexRestClient.class);
But every time I get null. Static registration of the instances doesn't work as the array of registered instances is empty. How can I correctly instantiate those both classes?