java - Can Guice assert that a singleton is not directly instantiated? -


is possible guice throw exception if try construct new instance of singleton?

for example:

public class mymodule extends abstractmodule {     @override     protected void configure() {         bind(mysingleton.class).in(singleton.class);     } }  @singleton public class mysingleton {     mysingleton() { /* ... */ } }  public class rightway {     public void withinjector() {         injector injector = guice.createinjector(new mymodule());         mysingleton mysingleton = injector.getinstance(mysingleton.class);     } }  public class anotherrightway {     private final mysingleton mysingleton;      @inject     public anotherrightway(mysingleton mysingleton) {         this.mysingleton = mysingleton;     } }  public class thewrongway {     public void directinstantiation() {         mysingleton mysingleton = new mysingleton(); // want exception here!     } } 

by making mysingleton's constructor package private, can limit scope mistakes, of course classes in same package can still throw spanner works. advantage here unit tests anotherrightway can pass mocks of mysingleton constructor.

or, make mysingleton's constructor protected, guice can handle, , can still mock making mocks extend mysingleton. mysingleton user same without knowing danger.

if guice can throw exception, can use reflection in unit tests construct mocks, users not accidentally create non-singleton version of mysingleton.

is possible? should use either package-private or protected , learn love bomb?

guice not magic. can't force outside of injector, no, can't that, , in fact shouldn't.

the best way, have noticed, make constructor of mysingleton package-private. way no 1 outside of package able construct guice. since package controlled you, safe assumption no 1 create mysingleton in other way via guice (using module, of course).

this not "bomb". package-private modifier intended purpose. assumed you control packages, fine make constructors , other things package-private , assume no 1 call them.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -