我的问题与@ronmamo在github上的Reflections库有关,并将其集成到我的Android项目中以动态访问从某个接口继承的所有类.

我对gradle或maven不太熟悉,所以这对我来说是一个学习过程,但是我遇到了障碍,不知道如何调试/找到答案.

正如@ronmamo建议here一样,我想在构建时生成一个xml文件,其中包含所有扫描的元数据,并让Reflections稍后在代码中使用它时收集它:

Although scanning can be easily done on bootstrap time of your

application – and shouldn’t take long, it is sometime a good idea to

integrate Reflections into your build lifecyle. With simple

Maven/Gradle/SBT/whatever configuration you can save all scanned

metadata into xml/json files just after compile time. Later on, when

your project is bootstrapping you can let Reflections collect all

those resources and re-create that metadata for you, making it

available at runtime without re-scanning the classpath – thus reducing

the bootstrapping time.

我不确定我是否完全了解“引导”在整个过程中的确切位置(就Android应用程序生命周期等而言,甚至还有构建时间?),所以我不确定确切地在哪里调用Reflections.collect().当前,当用户到达程序中的某个点时,我稍后会在我的应用程序中调用它.

从几个stackoverflow帖子和git自述文件中,我现在想出了这一点:([…]表示删除了不相关的代码)

build.gradle(Module:app):

dependencies {

[...]

compile 'org.reflections:reflections:0.9.11'

}

build.gradle(项目:MyProject):

buildscript {

repositories {

jcenter()

mavenCentral()

}

dependencies {

classpath 'com.android.tools.build:gradle:2.3.3'

classpath 'org.reflections:reflections:0.9.11'

}

}

allprojects {

repositories {

jcenter()

}

}

task runReflections {

doLast {

org.reflections.Reflections("f.q.n").save("${sourceSet.main.output.classesDir}/META-INF/reflections/myproject-reflections.xml")

}

}

task clean(type: Delete) {

delete rootProject.buildDir

}

然后在我的代码中(通过用户输入有时会到达该类,而不是在应用启动时加载):

Reflections reflections = Reflections.collect();

Set> allClasses = reflections.getSubTypesOf(MyInterface.class);

由于未实例化“ reflections”并且其值为“ null”,因此将生成以下异常:

Attempt to invoke virtual method 'java.util.Set org.reflections.Reflections.getSubTypesOf(java.lang.Class)' on a null object reference

我知道生成的.xml文件驻留在进行构建的计算机上,并且我不确定这是否也会传输到android设备,所以我的猜测是这失败的原因.但是什么时候我的Java代码在apk传输并在我的android设备上运行之前可以访问此文件?

我尝试过从不同角度以多种不同方式谷歌搜索,但是我似乎找不到能使反射在Android中工作的解决方案.我理解这里解释的原理,并且似乎最好在构建时在xml文件中生成信息,以使类信息在运行时可用.但是如何正确设置呢?

谢谢

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐