【发布时间】:2016-02-11 02:08:06
【问题描述】:
我有一个代码简介,它对 scala 类文件进行一些反思并寻找注释,类似于
// Create a new class loader with the directory
val cl = new URLClassLoader(allpaths.toArray)
getTypeNamesFromPath(sourceDir).map(s => {
val cls = cl.loadClass(s)
cls.getAnnotations.map(an =>
an match {
case q: javax.ws.rs.Path => println("found annotation")
case _ =>
})
})
此代码在 jar 中组装并使用 java -jar 运行时打印“找到的注释”,但从 sbt run 运行时不打印任何内容。
sbt 版本是 13.8, 斯卡拉版本 2.11.7
为了完整性
private def getTypeNamesFromPath(file: File, currentPath: mutable.Stack[String] = new mutable.Stack[String]()): List[String] = {
if (file.isDirectory) {
var list = List[String]()
for (f <- file.listFiles()) {
currentPath.push(f.getName)
list = list ++ getTypeNamesFromPath(f, currentPath)
}
return list
}
if (currentPath.isEmpty)
throw new IllegalArgumentException(file.getAbsolutePath)
currentPath.pop()
if (file.getName.endsWith(".class")) {
return List(currentPath.foldRight("")((s, b) => if (b.isEmpty) s else b + "." + s) + "." + file.getName.stripSuffix(".class"))
}
return List()
}
【问题讨论】:
-
什么是
getTypeNamesFromPath(sourceDir)?sourceDir实际上是源目录,还是包含.class文件的目录? -
sourceDir 是 ./target/scala_2.11/classes 文件夹的目录,getTypeNamesFromPath 只是一种从包文件夹结构中构造类型名称的方法,我发布了上面的方法