有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从Apple Script运行Java的applescript

我对苹果脚本非常陌生,所以请容忍我。我需要使用applescript运行一个.jar文件,因为jar是不可执行的,所以我调用了classcom.path.to.myClass。我的苹果脚本如下所示-

display alert "You are about to start the image rename process." buttons {"OK", "Cancel"}
set theAnswer to button returned of the result
if theAnswer is "OK" then
    do shell script "java -classpath ./ImageRename_JAVA-1.0.0.jar:. com.mff.image.rename.Main"
else
    say "Exit"
end if

applescript和ImageRename_JAVA-1.0.0.jar都在同一个目录中,但是当我运行脚本时,它会给我一个错误-

error "Exception in thread \"main\" java.lang.NoClassDefFoundError: com/mff/image/rename/Main
Caused by: java.lang.ClassNotFoundException: com.mff.image.rename.Main
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)" number 1

我把classpath设置错了吗?如果是,正确的方法是什么?另外,我如何向classpath添加更多的jar

当我从Terminal运行下面的命令时,它运行得很好

$ java -classpath ./ImageRename_JAVA-1.0.0.jar:. com.mff.image.rename.Main

我知道使用JAR Bundler可以以更好的方式完成,但我无法控制JAR和其他人开发的。是否有一种方法可以将应用程序中的所有JAR包含在YourApplicationName.app/Contents/MacOS/Resources/Java/目录下,并使用类路径中的那些


共 (1) 个答案

  1. # 1 楼答案

    我不认为你能保证do shell script中的工作目录是什么,但你可以用这样的方法来解决:

    set scriptPath to the POSIX path of (path to me)
    do shell script "SCRIPTDIR=`dirname " & scriptPath & "` ; " ¬
        & "java -classpath $SCRIPTDIR/ImageRename_JAVA-1.0.0.jar:$SCRIPTDIR com.mff.image.rename.Main"
    

    要向类路径添加额外的JAR,可以利用java命令提供的快捷方式,其中以*结尾的类路径条目包括给定目录中的所有.jar文件

    do shell script "java -classpath " ¬
      & "/Applications/Something.app/Contents/Resources/Java/\\* com.example.MyClass"
    

    需要对*进行反斜杠转义,以防止其被shell扩展,并且当反斜杠本身位于AppleScript字符串文本中时,需要对其进行反斜杠转义,因此\\*