简体   繁体   English

如何编写枚举对象的自定义提供程序?

[英]How to write custom provider for enum objects?

I am using Google Guice 4.1.0 for writing the provider. 我正在使用Google Guice 4.1.0编写提供程序。 But while Injecting the object of enum getting error (Error in custom provider, java.lang.IllegalArgumentException: Cannot reflectively create enum objects) 但是在注入枚举对象时会出错(自定义提供程序中的错误,java.lang.IllegalArgumentException:无法以反射方式创建枚举对象)

I tried removing the constructor from enum with @Inject annotation and adding @NoArgsConstructors and @AllArgsConstructors but getting error that enum must have either one constructor with @Inject annotation or one and only one constructor without parameter. 我尝试从带有@Inject批注的枚举中删除构造函数,并添加@NoArgsConstructors和@AllArgsConstructors,但出现错误,即枚举必须具有一个带有@Inject批注的构造函数或一个只有一个不带参数的构造函数。

My enum : 我的列举:

@AllArgsConstructor
@Getter
public enum IngestionMode {
    HAZELCAST(HazelcastMapCache.class),
    NEW_INGESTION(IngestionDataStoreCache.class);

    @Inject
    IngestionMode(){
        cacheTypeClass = HazelcastMapCache.class;
    }

    public Class cacheTypeClass;
}

Corresponding Provider: 对应提供者:

@Provides
@Singleton
public IngestionMode getIngestionOperatingMode() {
        return IngestionMode.HAZELCAST;
}

HazelcastMapCache and IngestionDataStoreCache are Normal Java classes. HazelcastMapCache和IngestionDataStoreCache是​​普通的Java类。

Using following enum causing error "enum must have either one constructor with @Inject annotation or one and only one constructor without parameter." 使用以下枚举会导致错误“枚举必须具有一个带有@Inject批注的构造函数,或者只有一个没有参数的构造函数”。

@RequiredArgsConstructor
@Getter
public enum IngestionMode {
    HAZELCAST(HazelcastMapCache.class),
    NEW_INGESTION(IngestionDataStoreCache.class);

    private final Class cacheTypeClass;
}

What can be possible workaround for this? 有什么可能的解决方法?

Simply do this in your Module : 只需在您的Module执行此操作:

@Override protected void configure() {
  bind(IngestionMode.class).toInstance(IngestionMode.HAZELCAST);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM