Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if JDK is available from within running JVM?

Tags:

java

jvm

liferay

Note: All the similar questions are answering this from the perspective of the shell (e.g. Is javac available? java -version or which java). I'm looking explicitly for the perspective of the currently running JVM.

There are programs that require to be run from within a JDK's JRE, not "just" a JRE. I'm wondering if there's a simple way to find out what my currently running program is executed in.

I'm looking for a generic way to figure this out, rather than an analysis of the program in question and duplicating its use of JDK features. That's why I'd prefer not to execute an external process testing if javac is on the path, if possible. I'm rather looking for some code that will run within a JDK, but fail within a JRE.

It could be Class.forName with a class that's only available in a JDK. It could be a system property. Or anything else.

If I have to execute an external process with javac: So be it. But I'd prefer something simpler and generic.

Clarification from deep down in the comments:

From time to time I'm running into this problem with Liferay, which requires to be run from within a JDK's JRE. I was entertaining the thought to just deploy another plugin that provides a userfriendly error message if run without a JDK available. I shy away from analyzing which code is the one failing in a JRE-only environment, and I don't want to modify Liferay's code, rather add my own plugin to do the analysis and warn.

like image 948
Olaf Kock Avatar asked Jul 19 '19 14:07

Olaf Kock


People also ask

How do you check if I have JDK?

1. Open command prompt and enter “java –version”. If installed version number is displayed.

How do I find my JDK path?

Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and in system variable try to find JAVA_HOME. This gives me the jdk folder.

Is JVM installed with JDK?

JVM (Java Virtual Machine) is a very important part of both JDK and JRE because it is contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for executing the java program line by line, hence it is also known as an interpreter.


2 Answers

javax.tools.ToolProvider.getSystemJavaCompiler() will return null if no compiler is available, and a JavaCompiler if it is.

Technically it just tells you if the compiler is available of course, but that in most scenarios will imply the existence of the JDK.

like image 146
Michael Berry Avatar answered Oct 11 '22 06:10

Michael Berry


Class.forName("com.sun.tools.javac.Main");

If there is no exception, it is a JDK.

It works with current JDKs, but it's probably not part of any official spec.

like image 41
Stefan Reich Avatar answered Oct 11 '22 04:10

Stefan Reich