0

我正在开发一个用于 Android 的 API。我想使用反射来访问在 android 活动类中实现的注释。我需要从我的 API 中反映出来。有办法吗?

我正在尝试将上下文传递给 API,但我可以获得注释所在的活动类。

该注解称为动作,如下:

@Action(
    name = "test",
    description = "this is just a test",
    inputs = {"no input"},
    output = {"no output"},
    controlURL = "/api/v1/"
) public void testAction (){
    /*
     * Implements here the Action!
     */
}

我用来反映它的方法:

private static void getAction() {
    if (D) Log.d(TAG, "getAction"); 

    Class classWithAction = AppContext.getClass();

    Annotation[] aAnnotations = classWithAction.getDeclaredAnnotations();
    for(Annotation a : aAnnotations)
        Log.d(TAG, a.toString());
 }
4

1 回答 1

1

在运行时发现所有使用特定注释注释的类通常需要类路径扫描。但是,没有简化的官方 API 来做这件事。这是因为由于类加载系统的设计,它总是不可避免地是一种黑客攻击。简而言之,原则上可以以完全不可控和任意的方式按需创建类。

然而,通常类路径丛林绝不是那么恶毒和充满陷阱,我们可以合理可靠地列出所有具有特定属性的类。有一个特定于 android 的障碍需要克服,但这还不错。基本上,诀窍是在应用程序的 .apk 存档中列出 classes.dex 文件的内容,一一加载其中包含的类,并反思性地检查所需的属性。您可以在此处获得更多详细信息(我的另一个答案),并且此博客文章包含此技术的相当完整的说明(这不是我的)。

于 2013-08-28T14:22:13.633 回答