简体   繁体   中英

How can I configure IntelliJ IDEA to allow a shebang in Java files

Context:

I often use a Java launching shebang to make my Java source files runnable as if they were scripts. I also regularly run projects directly out of IntelliJ IDEA. Many of my Java files start with #!/path/to/my/java/launcher .

I realize that this practice is questionable in all but the most basic of testing scenarios, but that's all I use it for.

This is convenient because I often run tests on multiple different servers when not testing locally in IDEA. It's cumbersome to point IDEA to different remote servers to run code on them, and much easier to just go to those servers (the code is already there, as it's stored on a network share) and run files with ./MyFile.java , or instruct others to do the same.

Problem:

If I have a file with a Java shebang in IDEA, it won't compile. The #! line (and the rest of the file) is detected as a syntax error by the IDE.

Question:

How do I configure IDEA to work with Java files containing a technically-invalid-syntax shebang?

Ideally, I'd be able to tell IDEA to "disregard lines that are first and start with #! in .java files when syntax-checking/compiling". However, I'd also be happy if I could configure a blanket "ignore the first line of all .java files when syntax-checking/compiling" rule.

Put more fundamentally: how do I get IDEA to support (compile, consider to be valid) Java files that contain a #! -prefixed first line?

What I've Tried:

  • I tried hacking the invocation of javac used by IDEA to use pipes/anonymous file descriptors and tail to exclude the first line; no such luck.
  • I've tried adding artifacts to strip out the first line as part of the build process, but this doesn't seem to help the syntax validation issue: even if the offending lines would be stripped out during the build, IDEA thinks the whole file is invalid syntax and can't be built.
  • I've tried using annotations to suppress the error, but those prevent the shebang from being on the first line, at which point the file can't be run as if it were a script.
  • I've tried messing with inspections in IDEA, but the fundamental compilation check behavior doesn't seem to be configurable (via the inspections interface, at least).

Is a build-and-run script unacceptable for some reason?

#!/bin/bash

set -e

CLASSPATH="..."

javac -cp "$CLASSPATH" "$1"
java -cp "$CLASSPATH:." "$1"

That seems no worse (and in fact better, since it's obvious and standard) than the shebang solution you link to, since it also relies on an external file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM