开发者

How to list all class names in the current package with Java?

开发者 https://www.devze.com 2022-12-21 16:49 出处:网络
In my Java project I need to list all class names in the current package, I usually run my app in two different modes : <1> From NetBeans, <2> From an executable jar file packaged by the NetBean

In my Java project I need to list all class names in the current package, I usually run my app in two different modes : <1> From NetBeans, <2> From an executable jar file packaged by the NetBeans.

My question is : How to write my program so that no matter which mode it is running, it can list all the class names in my app. Because when I run it in the NetBeans mode I can look into the src/ directory to list the class names, but when run in the packaged executable jar file mode on another machine, the src/ dir isn't there, so if in my program I try to list jar entries and find开发者_StackOverflow社区 the class names that way, it won't work when run in NetBeans, because it isn't jared yet.

I know I can try to detect which mode it is running under and handle differently, but is there a better way to do it without knowing which mode it is running under ?


I wonder if the following approach would solve my problem :

http://snippets.dzone.com/posts/show/4831

I tried : getClasses(".") to get current package's classes, it didn't work, why ?

Frank


Provided you are not using any dynamic class loaders you can search the classpath and for each entry search the directory or JAR file.


You can not tell which classes are in a package. This is because everyone can add other classes to your packages (for instance from other jar files).

However there are functions in the java API to look into jar files. It wouldn't be entirely independent of the way of running though.

0

精彩评论

暂无评论...
验证码 换一张
取 消