Search code examples
androiddependency-injectionguice

Can I use Guice on Android?


Is Guice compatible with android ? I ask because on a fresh new project I get a weird error on the injector creation see below:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}:   
[...]  
com.google.common.util.concurrent.UncheckedExecutionException: 
Caused by: com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException: Unable to load cache item  
[...]  
Caused by: java.lang.UnsupportedOperationException: can't load this type of class file
        at java.lang.ClassLoader.defineClass(ClassLoader.java:591)  
[...]

Here is the piece of code that is crashing (inside my MainActivity):

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        Guice.createInjector(MyModule()) // The exception happens here

        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }
    }

Here is my module:

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(DummyInterface.class).to.(DummyImplementation.class);
   }

Whenever I use toInstance() intead of to() statement the app runs fine which makes me think that guice reflection capabilities are not compatible with Android.
Is it a correct assumption or am I doing something wrong? Because I never seen anywhere that Guice cannot be used on Android.


Solution

  • Use the no_aop version of Guice:

    <dependency>
      <groupId>com.google.inject</groupId>
      <artifactId>guice</artifactId>
      <version>4.2.3</version>
      <classifier>no_aop</classifier>
    </dependency>