gpt4 book ai didi

java - 如何知道一个类是来自 JRE 还是来自外部 Jar?

转载 作者:行者123 更新时间:2023-11-29 03:45:54 24 4
gpt4 key购买 nike

有人知道是否有可能(有图书馆)知道 Class<?> 是否存在吗?变量是否包含在 JRE 中?

这是我想要的:

Class<String> stringClass = String.class;
System.out.println(TheMagickLibrary.isJREClass(stringClass)); // should display true

Class<AnyClass> anotherClass = AnyClass.class;
System.out.println(TheMagickLibrary.isJREClass(anotherClass)); // should display false

最佳答案

我可以为您提供 2 种解决方案。

  1. 获取类包,查看是否以java.sun.com.sun.开头
  2. 获取类的类加载器:
Returns the class loader for the class.  Some implementations may use
null to represent the bootstrap class loader. This method will return
null in such implementations if this class was loaded by the bootstrap
class loader.

如您所见,他们说“某些实现可能会返回 null”。这意味着对于这些实现 clazz.getClassLoader() == null 意味着该类由引导类加载器加载,因此属于 JRE。顺便说一句,这适用于我的系统(Java(TM) SE Runtime Environment (build 1.6.0_30-b12))。

如果没有查看ClassLoader#getParent()的文档:

 Returns the parent class loader for delegation. Some implementations may
use <tt>null</tt> to represent the bootstrap class loader. This method
will return <tt>null</tt> in such implementations if this class loader's
parent is the bootstrap class loader.

同样,如果当前类加载器是 Bootstrap ,一些实现将返回 null。

最后我推荐以下策略:

public static boolean isJreClass(Class<?> clazz) {
ClassLoader cl = clazz.getClassLoader();
if (cl == null || cl.getParent() == null) {
return true;
}
String pkg = clazz.getPackage().getName();
return pkg.startsWith("java.") || pkg.startsWith("com.sun") || pkg.startsWith("sun.");
}

我相信这对于 99% 的情况来说已经足够了。

关于java - 如何知道一个类是来自 JRE 还是来自外部 Jar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10917353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com