开发者

Self-modify the classpath within a Scala script?

I'm trying to replace a bunch of Linux shell scripts with Scala scripts.

One of the remaining challenges is how to scan an entire directory of JARs and place them into the classpath. Currently this is done in the shell script prior to invoking the scala JVM. I'd like to eliminate the shell script completely.

Is there an elegant scala idiom for this?

I have found this other question but in Java it seems hardly worthwhile to mess wit开发者_运维百科h it: How do you change the CLASSPATH within Java?


The JVM itself supports a wild-card notation in the class-path. If /foo/bar is a directory holding JAR files, all of which you want to be in the class-path, you can include /foo/bar/* in the class-path instead of enumerating each JAR file individually.

I'm not sure that will suffice for your purposes, but it's handy when it's suitable.


Um, this is directly supported, you don't even need the java support. Did you try it?

scala -cp '/foo/bar/*'


This script browses the lib dir recursively:

import java.io.File
import java.util.regex.Pattern

def cp(root: File, lib: File): String = {
  var s = lib.getAbsolutePath.replaceFirst(
    Pattern.quote(root.getAbsolutePath) + File.separator + "*", "") +
    File.separator + "*"
  for (f <- lib.listFiles; if f.isDirectory)
    s += File.pathSeparator + cp(root, f)
  s
}

For example:

/project
   lib
   |__dep
   |__dep2
     |__dep3

You call:

var f = new File("/path/to/project")
cp(f, f)

Result:

/*:lib/*:lib/dep2/*:lib/dep2/dep3/*:lib/dep/*
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜