Skip to content

Instantly share code, notes, and snippets.

@kadiryumlu
Created December 25, 2025 11:50
Show Gist options
  • Select an option

  • Save kadiryumlu/38ccafc89f791bc9c12d6ee45f9d0c4c to your computer and use it in GitHub Desktop.

Select an option

Save kadiryumlu/38ccafc89f791bc9c12d6ee45f9d0c4c to your computer and use it in GitHub Desktop.
ServiceLocator class for Java
import java.util.HashMap;
import java.util.Map;
public final class ServiceLocator {
private static final Map<Class<?>, Object> services = new HashMap<>();
private ServiceLocator() {
//
}
public static <T> void register(Class<T> type, T service) {
services.put(type, service);
}
public static <T> void unregister(Class<T> type) {
services.remove(type);
}
@SuppressWarnings("unchecked")
public static <T> T get(Class<T> type) {
Object service = services.get(type);
if (service != null) {
return (T) service;
}
throw new RuntimeException("Service not found: " + type.getName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment