As you describe it, no, there isn't a super elegant improvement you can
make.  Other than, perhaps, injecting Provider<HttpServletRequest> and then
invoking get() in the try block.

There might be a better solution to the general problem, however.  What is
the general problem?

On Tue, Jan 11, 2011 at 8:46 PM, Ambience <[email protected]> wrote:

> I need to inject a field only if it is available in the current scope,
> and null otherwise. For example:
>
> public class Thinger implements Provider<SomeSuch> {
>    public @Inject(optional=true) HttpServletRequest request;
>
>    public SomeSuch get() {
>        return request == null ? new WhosIt() : WhatsIt();
>    }
> }
> However, if HttpServletRequest is bound (which it is) but not in
> scope, I get a ProvisioningException. I have not been able to find an
> elegant way to do this so I am relegated to do something like.
>
> HttpServletRequest request = null;
> try {
>    request = injector.getInstance(HttpServletRequest.class);
> } catch(ProvisioningException e) {}
>
> Which just feels all manner of wrong. Is there a proper way to do this?
>
> --
> You received this message because you are subscribed to the Google Groups
> "google-guice" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected]<google-guice%[email protected]>
> .
> For more options, visit this group at
> http://groups.google.com/group/google-guice?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"google-guice" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/google-guice?hl=en.

Reply via email to