java - Android Annotation处理器访问资源(assets)

标签 java android android-resources annotation-processing

我想在我的注释处理器中访问我的 andoid studio 项目中的资源。

我首先尝试使用 filer 的 getResource 方法:

FileObject fo = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, "", "src/main/res/layout/activity_main.xml");

,但它总是抛出一个异常,只是将“src/main/res/layout/activity_main.xml”作为消息返回。

接下来我想我试过的是

this.getClass().getResource("src/main/res/layout/activity_main.xml")

,但这总是返回 null。

我最后想用的是这个:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
            Iterable<? extends File> locations = fm.getLocation(StandardLocation.SOURCE_PATH);
            for (File file : locations) {
                System.out.print(file.getAbsolutePath());
            }

,但是会抛出空指针异常

最佳答案

我使用以下方法从我的注释处理器中获取布局文件夹:

private File findLayouts() throws Exception {
        Filer filer = processingEnv.getFiler();

        JavaFileObject dummySourceFile = filer.createSourceFile("dummy" + System.currentTimeMillis());
        String dummySourceFilePath = dummySourceFile.toUri().toString();

        if (dummySourceFilePath.startsWith("file:")) {
            if (!dummySourceFilePath.startsWith("file://")) {
                dummySourceFilePath = "file://" + dummySourceFilePath.substring("file:".length());
            }
        } else {
            dummySourceFilePath = "file://" + dummySourceFilePath;
        }

        URI cleanURI = new URI(dummySourceFilePath);

        File dummyFile = new File(cleanURI);

        File projectRoot = dummyFile.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();

        return new File(projectRoot.getAbsolutePath() + "/src/main/res/layout");
    }

关于java - Android Annotation处理器访问资源(assets),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225786/

相关文章:

java - 无法在 Java 中解析日期年份

java - Insert } to Complete ClassBody 错误,即使有匹配的大括号

android - layoutParams 不变

android - 以编程方式将 TextView 颜色设置为 <selector>

java - 有没有办法改进这个正则表达式代码?

javascript - Stripes:无法添加到通过 javascript 动态创建的表格中

android - 从 RealmList 中删除 RealmObject

android - 在为较早的查询迭代游标的同时执行新的 SQLite 查询是否安全? (安卓)

java - 如何访问自定义搜索建议提供程序中的本地化字符串?

android - 我们如何使用数据绑定(bind)从字符串资源中获取 SpannedString 对象?