If you play with a dirty reflection, I'm afraid you will have to work with instances instead of classes. From @JonSkeet :
Singleton allows you to access one created instance - this instance (or rather, a link to this instance) can be passed as a parameter to other methods and is treated as a regular object.
A static class allows only static methods.
This is exactly what you are trying to do: passing the configuration as a parameter.
I would create an abstract class defining default values:
public abstract class Configuration { public int getFoo() { return 1; } public int getBar() { return 2; } }
Then one singleton for a specific configuration:
public final class DefaultConfiguration extends Configuration { public static final Configuration INSTANCE = new DefaultConfiguration(); private DefaultConfiguration() {}
Finally, in Main :
public class Main { private final Configuration config; public Main() { this(DefaultConfiguration.INSTANCE); } public Main(Configuration config) { this.config = config; } }
Also, note that Java 8 allows you to implement default methods in interfaces; Configuration can be an interface:
public interface Configuration { default int getFoo() { return 1; } default int getBar() { return 2; } }
sp00m
source share