java—在运行时检测缺少或存在jvm的project loom技术

szqfcxe2  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(373)

ProjectLoom现在可以在Java16的特别早期版本中使用。
如果我在一个缺少projectloom技术的java实现上运行基于loom的应用程序,有没有一种方法可以在我的应用程序启动的早期优雅地检测到这一点?
我想写这样的代码:

if( projectLoomIsPresent() )
{
    … proceed …
}
else
{
    System.out.println( "ERROR - Project Loom technology not present." ) ;
}

如何实现 projectLoomIsPresent() 方法?

uurity8g

uurity8g1#

方法1:

return System.getProperty("java.version").contains("loom");

方法2:

try {
    Thread.class.getDeclaredMethod("startVirtualThread", Runnable.class);
    return true;
} catch (NoSuchMethodException e) {
    return false;
}
gorkyyrv

gorkyyrv2#

您可以检查project loom之前不存在的功能:

import java.util.Arrays;

public static boolean projectLoomIsPresent() {
    return Arrays.stream(Thread.class.getClasses())
        .map(Class::getSimpleName)
        .anyMatch(name -> name.equals("Builder"));
}

无需捕获异常:

import java.lang.reflect.Method;
import java.util.Arrays;

public static boolean projectLoomIsPresent() {
    return Arrays.stream(Thread.class.getDeclaredMethods())
        .map(Method::getName)
        .anyMatch(name -> name.equals("startVirtualThread"));
}

相关问题