1

有人知道是否有可能(是否有库)知道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
4

1 回答 1

4

我可以为您提供 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 运行时环境(构建 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.

同样,如果当前类加载器是引导程序,某些实现将返回 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% 的情况来说已经足够了。

于 2012-06-06T15:59:15.193 回答