I am using a 3rd party library that, among other things, loads classes 
specified in an xml file. Something like:

<element class="some.package.name.MyClass">

The documentation specifies when writing custom classes to be loaded by 
their API, you should use a no-args constructor. In the source code, they 
call Class.newInstance().

I would like to write a custom class for use with their API, because I want 
the custom behavior to do something with a dependency written by me. 
However, because of the way the object is created, I cannot use Guice to 
inject this dependency.

The solution I came up with is to do something like this:

public class DependencyContainer {
    @Inject private volatile static DependencyContainer instance;
    @Inject private volatile TheDependency dep;

    public TheDependency getDependency() {
        return dep;
    }

    public static DependencyContainer getInstance() {
        return instance;
    }
}

public class MyImpl extends ThirdPartyInterface {
    private TheDependency dep = null;

    public void doThirdPartyTask() {
        if (dep == null) {
            if(attemptGetDependency() == null) return;
        }
        // behavior
    }

    private TheDependency attemptGetDependency() {
        dep = DependencyContainer.getInstance().getDependency();
        return dep;
    }
}

I can then load the dependency with requestStaticInjection. Is this the 
preferred way to do this task? Is there a better, less ugly way?

-- 
You received this message because you are subscribed to the Google Groups 
"google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/google-guice.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to