Wang Liang
Wang Liang

Reputation: 4434

At java code, how i can check jdk version to compile below java code?

// monitor.freeMemory = bean.getFreeMemorySize();//jdk 15
// monitor.maxMemory = bean.getTotalMemorySize();
// monitor.systemLoadAverage = bean.getCpuLoad();


monitor.freeMemory = bean.getFreePhysicalMemorySize();//jdk 13
monitor.freeMemory = bean.getTotalPhysicalMemorySize();
monitor.systemLoadAverage = bean.getSystemCpuLoad();

I want to use above code without comment

Upvotes: 0

Views: 212

Answers (2)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18899

Until now this is not possible. At least not something that you think of, like a clean If/else condition. If we hack deep enough we can make it happen, in a very dirty way though.

That's the reason that methods get deprecated. They don't throw things out of the window so that the project must be compiled with another method. They provide for enough time those deprecated methods so that you can move forward safely.

That is also the case in your question. Your project could compile with either JDK 13 or JDK 15 using the same code.

com.sun.management.OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
bean.getFreePhysicalMemorySize();
bean.getTotalPhysicalMemorySize();
bean.getSystemCpuLoad();

This code will be able to compile and function from JDK 11 up to all new versions of JDK. If you switch to JDK 14 though, you will receive a deprecated warning.

enter image description here

Considering that JDK 11 is a LTS version, they could not throw methods out of the window. Most probably they will be available also to the next LTS version.

Upvotes: 1

mnikolic
mnikolic

Reputation: 602

Java does not have a conditional compilation, so some workarounds have to be made. One approach is to make an interface like this:

interface monitor {
  public void getFree();
  public void getTotal();
  public void getCpu();
}

Implementation of this interface should call appropriate methods using reflection depending on the JVM version. Something like this (conceptually):

public void getFree() {
    if (System.getProperty("java.version").equals(JDK_15_VERSION)) {
        Class myclass = Class.forName("my.class.JDK_15_NAME");
        Object myobject = myclass.newInstance();
        Method method = myclass.getDeclaredMethod("FREE_MEM_JDK_15_METHOD", null);
        method.invoke(obj, null);
    }
    else {
        Class myclass = Class.forName("my.class.JDK_13_NAME");
        Object myobject = myclass.newInstance();
        Method method = myclass.getDeclaredMethod("FREE_MEM_JDK_13_METHOD", null);
        method.invoke(obj, null);
    }
}

Upvotes: 1

Related Questions