0

Is it ok to use javax.lang.model.SourceVersion to determine the JRE version?

If it is, which one is preffered?

int version = SourceVersion.latest().ordinal();
// or
int version = SourceVersion.latestSupported().ordinal();

Bonus points to whomever explains when SourceVersion#latest() and SourceVersion#LatestSupported() can differ.

PS. I am aware of Getting Java version at runtime

Community
  • 1
  • 1
Darsstar
  • 1,885
  • 1
  • 14
  • 14

2 Answers2

1

SourceVersion.latest() returns latest source version that can be modeled.

SourceVersion.latestSupported() Returns the latest source version fully supported by the current execution environment. {@code RELEASE_5} or later

When I checked the sourcecode at java 7 sourceVersion srcCode

following snippet explains the internal behavior

public static SourceVersion latest() { 
 return RELEASE_7;
}

private static SourceVersion More ...getLatestSupported() {
       try {
           String specVersion = System.getProperty("java.specification.version");
           if ("1.7".equals(specVersion))
               return RELEASE_7;
            else if ("1.6".equals(specVersion))
                return RELEASE_6;
        } catch (SecurityException se) {}

        return RELEASE_5;
  }

Hope it clarifies your doubts

Shirishkumar Bari
  • 2,692
  • 1
  • 28
  • 36
1

To answer your question-

when SourceVersion#latest() and SourceVersion#LatestSupported() can differ.

As you are aware by now that the latestSupported is derived from the system property java.specification.version.

So for example if you are running your application on JAVA 8, then:

SourceVersion#latest() will alwasy be RELEASE_8

SourceVersion#LatestSupported() could be any of the following:

  1. RELEASE_5
  2. RELEASE_6
  3. RELEASE_7
  4. RELEASE_8

based on the java.specification.version in the the jar/war. Technically this can be a user defined value and is very useful when you develop an api (Which can be distributed to various other developers/applications)

avijendr
  • 3,958
  • 2
  • 31
  • 46