I was wondering if there is a Java API that could tell you whether a particular language feature (e.g. "diamond" operator) is available on the current platform.
(In other words, what I'm trying to do is analogous to "browser sniffing" in JavaScript.)
This would be really handy in meta-programming (writing a Java program that generates Java source code.
The best solution I've found so far is to parse System.getProperty("java.specification.version")
and check whether it's ≥ the version that introduced this feature, but I'm not 100% sure that this property is available in all JVMs (or even whether it conforms to the same syntax in all JVMs). Another minor annoyance with this approach is that you have to take the extra step of looking up which version of Java introduced the language feature you're interested in. Not a big deal, since that info is pretty easy to google, but ideally it would be nice if there was an API that could readily provide the info, for example:
code.append("Map<Integer, String> map = ");
if (javax.meta.JavaVersion.getCurrentVersion().supportsDiamond()) {
code.append("new Map<>();");
} else {
code.append("new Map<Integer, String>();");
}
Obviously there's no package named javax.meta
, but I was wondering if there might already be an existing solution for this problem that's cleaner than parsing the "java.specification.version"
property.
Update: I just realized that Package#getSpecificationVersion()
also provides the same value as System.getProperty("java.specification.version")
but is probably more reliable, because System properties are mutable. In other words, the best way to get the Java spec version is probably to call Package#getSpecificationVersion()
on any "built-in" package. For example: String.class.getPackage().getSpecificationVersion()