有没有办法强制类加载器加载一个包,即使它的类没有被加载吗? [英] Is there a way to force a classloader to load a package even if none of its classes have been loaded?

查看:150
本文介绍了有没有办法强制类加载器加载一个包,即使它的类没有被加载吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设一个java代码库有一个名为com.example的包。

Let's say a java codebase has a package called "com.example".

在运行时,我们可以通过调用

At runtime, we can get this Package by calling

Package p = Package.getPackage( "com.example" ); //(returns null)

甚至通过调用

Packages[] ps = Package.getPackages();

问题是 - 如果ClassLoader尚未从包中加载任何类,可用于这些函数调用。我们可以强制它通过强制加载包中的一个类来加载包,如下所示:

The problem is - if the ClassLoader has not yet loaded any class from the package, it won't be available to these function calls. We can force it to load the package by force-loading one of the classes in the package first, like this:

this.getClass().getClassLoader().loadClass( "com.example.SomeClass" );
Package p = Package.getPackage( "com.example" ); //(returns non-null)

然而,这是hacky并且需要提前知道名称

However, this is hacky and requires knowing ahead of time the name of some class that belongs to the package.

所以问题是 - 有没有办法通过名称获取一个Package的实例,无论ClassLoader是否做什么?我的假设关于如何类加载/包似乎在这种情况下工作准确吗?

So the question is - is there any way to get an instance of Package by name, regardless of whether or not the ClassLoader has done anything? Are my assumptions about how classloading/packages seem to work in this situation accurate?

推荐答案

或者,您可以使用类根目录作为起点,遍历所有* .class文件和子目录。这只会工作,如果你知道你的所有.class文件将事先驻留在哪里。

Alternatively you could use the class root directory as a starting point and walk through all *.class files and sub directories. This would only work if you know where all your .class files will reside beforehand.

这一切的原因是Java有动态类加载,所以类可以加载运行时从编译时未知的位置或甚至在启动时。因此,包的概念只是一个用于加载类的命名空间,而不是可用于查找的目录。

The cause of all this is that Java has dynamic classloading, so classes can be loaded at runtime from locations not known at compile time or even at startup time. Therefore the concept of a package is just a namespace for loaded classes, not a directory which you can use to look them up.

这篇关于有没有办法强制类加载器加载一个包,即使它的类没有被加载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆