Class OptionalConstructorParam<T>

  • All Implemented Interfaces:
    java.util.function.Supplier<T>

    public final class OptionalConstructorParam<T>
    extends java.lang.Object
    implements java.util.function.Supplier<T>

    Workaround for optional constructor parameters with Guice. Modeled after the Guava Optional class, but you cannot create your own Optional because the constructor is private, so just adopting the look and feel of it.

    Unfortunately, this does not support optional bindings which use @Named; that annotation on the value in the constructor, eg:

    public Foo(@Named("bar") OptionalConstructorParam<MyObject> theParam)

    Because the @Inject is inside OptionalConstructorParam and that's where the injection actually takes place, the @Named annotation is essentially ignored. If you could place @Named inside this class, with a parameterized value for the name, that would work as expected, but annotation values have to be consts, so there's no way to pass in the name to the annotation. So if you want to use @Named w/ an optional constructor parameter, you basically have to duplicate the Guice part of this class locally and use the @Named annotation explicitly.

    Since:
    0.6.5
    Version:
    4.0
    Author:
    Michael Grove
    See Also:
    Guice Frequently Asked Questions
    • Constructor Detail

      • OptionalConstructorParam

        @Inject
        public OptionalConstructorParam()
      • OptionalConstructorParam

        public OptionalConstructorParam​(T theValue)
    • Method Detail

      • get

        public T get()
        Specified by:
        get in interface java.util.function.Supplier<T>
      • or

        public T or​(T theDefault)
      • or

        public T or​(java.util.function.Supplier<? extends T> theDefault)
      • orNull

        public T orNull()
      • asOptional

        public java.util.Optional<T> asOptional()
      • equals

        public boolean equals​(java.lang.Object o)
        Overrides:
        equals in class java.lang.Object
      • hashCode

        public int hashCode()
        Overrides:
        hashCode in class java.lang.Object
      • toString

        public java.lang.String toString()
        Overrides:
        toString in class java.lang.Object
      • isPresent

        public boolean isPresent()