简体   繁体   English

获取 kotlin 类因字符串失败,但使用常量 - 动态功能

[英]Get kotlin class failed with string but works with constant - on dynamic feature

I just call a method class through this line :我只是通过这一行调用一个方法类:

val instance = Class.forName(nameClass).kotlin.objectInstance

When I set the nameClass with a constant value (see below) it's work.当我将 nameClass 设置为常量值(见下文)时,它就起作用了。

private const val PROVIDER_CLASS = "com.abc.xyz.feature.DynamicFeatureImpl\$Provider"

fun method() {
    val instance = Class.forName(PROVIDER_CLASS).kotlin.objectInstance
}

But, when I set the nameClass to string (not constant), like this但是,当我将 nameClass 设置为字符串(不是常量)时,就像这样

fun method() {
    val nameClass = "com.abc.xyz.feature.DynamicFeatureImpl\$Provider"
    val instance = Class.forName(nameClass).kotlin.objectInstance
}

it's not work and throw java.lang.ClassNotFoundException .它不起作用并抛出java.lang.ClassNotFoundException ClassNotFoundException

I have trying make log, check is the value PROVIDER_CLASS are same with the string nameClass, and the result is true .我尝试制作日志,检查值 PROVIDER_CLASS 是否与字符串 nameClass 相同,结果为true but the code not work with string one.但代码不适用于字符串一。 My goal is make the code work through variable className string as parameter.我的目标是通过变量 className 字符串作为参数使代码工作。

So, what wrong with the code?那么,代码有什么问题呢? it's make me confused.这让我很困惑。

Update: Actually it's call a method from dynamic feature with dagger.更新:实际上它是用匕首从动态特性中调用一个方法。 my reference this medium post我参考了这篇中篇文章

I solved this problem by adding rules to proguard-rules.pro on root project我通过在根项目的proguard-rules.pro中添加规则解决了这个问题

-keep class com.abc.xyz.feature.DynamicFeatureImpl {
   com.abc.xyz.feature.DynamicFeatureImpl$Provider Provider;
}

-keep class com.abc.xyz.feature.DynamicFeatureImpl$Provider {   
   *;
}

the rules that I've added before is only on consumer-rules (the dynamic module) but in fact it's not enough我之前添加的规则仅在消费者规则(动态模块)上,但实际上还不够

-keep class com.abc.xyz.feature.** { *; }
-keep class com.abc.xyz.feature.di.** { *; }

It's make me confused a couple days, hope this will help somebody if find this issue.这让我困惑了几天,希望这对发现这个问题的人有所帮助。

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

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