Gradle:使用注释从打包(jar)中排除某些文件

Nik*_*hil 5 java annotations gradle

我正在寻找一种解决方案来排除某些标记有特定注释的文件以打包在 jar 中(可以编译但不是创建的 jar 的一部分)。

我已尝试以下步骤

  1. 使用以下命令创建类加载器:sourceSets.main.output +configurations.runtime
  2. 在编译的类中递归检查,使用 ClassLoader.loadClass 加载类并检查注释是否存在(Class.isAnnotationPresent)

任何指示都会有帮助。

Nik*_*hil 1

我很久以前就能实现这个问题,但忘记了我已经在这里发布了这个问题。

我以前使用的解决方案实际上非常简单 - 使用 gradlejar任务 -

jar {
    excludes = excludedFiles(sourceSets.main.allSource.files)
    baseName = artifactName
    version = artifactVersion
}
Run Code Online (Sandbox Code Playgroud)

并定义excludedFiles函数来查找提供的源目录中的文件 -

def excludedFiles(Collection<File> files) {
   List<String> classes = new ArrayList<>()
   files.each { file ->
   if (file.isDirectory()) {
     excludedFiles(Arrays.asList(file.listFiles()))
   }
   else {
     if (file.text.contains("@YourAnnotation") && file.text.contains("import foo.bar.YourAnnotation")) {
       classes += getClassName(file.absolutePath)
     }
   }
 }
 return classes
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。