在Kotlin中使用@AutoAnnotation,投诉方法必须是静态的

时间:2019-01-06 03:18:16

标签: kotlin annotations

参考https://google.github.io/dagger/multibindings.html,有此代码

@AutoAnnotation
static MyKey createMyKey(String name, Class<?> implementingClass, int[] thresholds) {
  return new AutoAnnotation_MyComponentTest_createMyKey(name, implementingClass, thresholds);
}

转换为Kotlin时,我在下面使用

companion object {
    @AutoAnnotation
    @JvmStatic
    fun createMyKey(name: String, implementingClass: Class<*>, thresholds: IntArray): MyKey {
        return AutoAnnotation_MainActivity_createMyKey(name, implementingClass, thresholds)
    }
}

它仍然在抱怨

error: @AutoAnnotation method must be static
    public final com.elyeproj.daggermultibinding.MyKey createMyKey(@org.jetbrains.annotations.NotNull()
                                                       ^    

无论有没有@JvmStatic,我都无法正常工作。有什么解决的办法吗?

2 个答案:

答案 0 :(得分:0)

以下对我有用。具有create key方法作为全局函数。

class HelloAutoAnnotations {
    fun execute() {
        println("HelloAutoAnnotations...")

        DaggerMyComponent.create().myMap().forEach(::println)
    }
}

@MapKey(unwrapValue = false)
private annotation class MyKey(val username: String, val password: String)

@Module
private class MyModule {
    @Provides
    @IntoMap
    @MyKey(username = "user1", password = "T0gether")
    fun providesUser(): String = "Rooney"

    @Provides
    @IntoMap
    @MyKey(username = "user2", password = "T0gether")
    fun provideUser(): String = "Doo"
}

@Component(modules = arrayOf(MyModule::class))
private interface MyComponent {
    fun myMap(): Map<MyKey, String>
}

@AutoAnnotation
private fun createMyKey(username: String, password: String): MyKey {
    return MyKeyCreator.createMyKey(username, password)
}

答案 1 :(得分:0)

根据文档:

  

在编译时不知道其键的地图

     

只有在编译时就知道地图的键,地图多重绑定才有效   时间,并可以在注释中表示。如果您的地图按键没有   符合这些约束,那么您将无法创建多边界地图,但是   您可以通过使用set multibindings绑定一组   然后可以将其转换为非多边界图的对象。

@Module
class MyModule {
  @Provides @IntoSet
  static Map.Entry<Foo, Bar> entryOne(...) {
    Foo key = ...;
    Bar value = ...;
    return new SimpleImmutableEntry(key, value);
  }

  @Provides @IntoSet
  static Map.Entry<Foo, Bar> entryTwo(...) {
    Foo key = ...;
    Bar value = ...;
    return new SimpleImmutableEntry(key, value);
  }
}

@Module
class MyMapModule {
  @Provides
  static Map<Foo, Bar> fooBarMap(Set<Map.Entry<Foo, Bar>> entries) {
    Map<Foo, Bar> fooBarMap = new LinkedHashMap<>(entries.size());
    for (Map.Entry<Foo, Bar> entry : entries) {
      fooBarMap.put(entry.getKey(), entry.getValue());
    }
    return fooBarMap;
  }
}

所以您也许应该尝试这种方法。

相关问题