使用java反射获取包名称 [英] Get package names using java reflections

查看:291
本文介绍了使用java反射获取包名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个单独的Java项目中获取所有包名称,我最好如何使用反射在Java中执行此操作?

I want to get all the package names from an separate Java project, how would I do this in Java preferably using reflections?

我已将项目导入到我的项目中构建路径,我尝试使用下面的代码来获取包名。

I have imported the project into my build path and I've tried using the code below to get the package names.

Package [] pack = Package.getPackages();

编辑:我没有使用jar文件,我刚刚导入了项目,因为它将在同一个目录中。我只需要我创建的包,特别是以某个目录开头的包。

I'm not using jar files, I have just imported the project as it will be in the same dir. I only need packages that I created, specifically packages which begin with a certain directory.

推荐答案

你真的不知道每一个包只使用 getPackages()在库中命名,因为它只列出类加载器已知的那些。这意味着如果某个类尚未从特定包中加载,那么它将不在列表中。

You really can't know every package name in the libraries by just using getPackages() as it only will list the ones known to the classloader. This means that if a class has not yet been loaded from a specific package, then it will be absent from the list.

使用zip文件处理例程打开jar文件,并按目录名读出包。使用此技术,您将发现所有包名称,甚至是那些尚未使用的包名称。基本上,任何包含 .class 文件的路径都是包名。

Use the zip file handling routines to open the jar files, and read out the packages by directory name. With this technique, you will discover all package names, even those that are not yet "in use". Basically, any path that contains a .class file is a "package name".

----已编辑进一步的细节表明没有使用JAR文件---

---- Edited as further details indicates JAR files are not being used ---

因为你没有使用JAR文件(为什么不呢?它们真的很棒!),你将不得不扫描目录。要找到目录,您需要切断类路径。获取类路径的方法是:

Since you aren't using JAR files (and why not? they're really good!), you will have to scan directories. To "find" the directories, you will need to chop up the class path. The way to get the class path is:

 String classpath = System.getProperty("java.class.path", null);

然后搜索每个起点下具有<$ c的所有目录$ c> .class 中的文件。一旦你掌握了所有这些,你就拥有了所有的软件包。

Then you do a search of all the directories under each "starting point" that has a .class file in it. Once you have all of those, you have all of the packages.

再一次,只要问问类加载器就不可能知道所有软件包,除非你能以某种方式保证类加载器已加载所有类(通常不加载)。

Again, it is not possible to know all the packages by just asking the classloader, unless you could somehow guarantee the class loader has loaded all of the classes (which it typically doesn't).

这篇关于使用java反射获取包名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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