问题
Short story
I need a system level way to set the java.awt.headless
property to true
for all java invocations. That is, using -Djava.awt.headless=true
is not an option, since java is being invoked from places I don't have access to (e.g. from within another tool written in Java/C/etc.)
Long story
I'm using a bunch of tools written in Java (specifically Adobe's Air ADT) that rely on AWT classes. When I run these tools on the console they work fine. But when I run them from an SSH session they fail with java.lang.InternalError: Can't connect to window server - not enough permissions
. Googling around I found that setting java.awt.headless to true will fix the problem. It doesn't, and that's because ADT itself spawns children Java processes without -Djava.awt.headless=true
.
Is there any system-level way to ensure this property is set whenever Java is invoked? Maybe some system awt property file or equivalent?
Worst case scenario I could try replacing /usr/bin/java
with a shell script that adds this argument to "$@"
but I'm hoping to avoid that. (Update: Just to ensure my theory is right, tried this shell script hack and it does solve the problem. Just hoping for a cleaner solution)
回答1:
It looks like support for JAVA_TOOL_OPTIONS
environment variable was added to the Sun/Oracle JVM at least by Java 6. It is described in Java 8 documentation. I haven't tested but it appears to be in the OpenJDK too. This appears to be a more standardized solution than the other answers here.
I was able to solve the issue I encountered with:
JAVA_TOOL_OPTIONS=-Djava.awt.headless=true ant ...
This successfully propagated the property to Gradle build scripts (./gradlew
) called from Ant. By comparison ant -Djava.awt.headless=true ...
did not propagate the property to subprocesses. Found this solution originally described in a Gradle-related gist on github.
回答2:
Use _JAVA_OPTIONS
instead of JAVA_OPTS
. _JAVA_OPTIONS
will get picked up automatically when you run java.
export _JAVA_OPTIONS=-Djava.awt.headless=true
adt ...
I know this is true on OS X. This indicates that this may work on Windows and Linux, as well.
回答3:
Seems there's no standard way to do this. This is the best I could come up with:
- Rename
/usr/bin/java
to/usr/bin/java.ori
Create the following
/usr/bin/java
replacement with 755 permissions:#!/bin/bash java.ori $JAVAOPT "$@"
Then you can use the environment variable
JAVAOPT
to set global java options. These will also be propagated to any java subprocess that may be spawned:export JAVAOPT=-Djava.awt.headless=true adt ...
来源:https://stackoverflow.com/questions/10627405/how-to-set-java-system-properties-globally-on-os-x