This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills and have John Sonmez on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Finding the packages for a source file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Finding the packages for a source file" Watch "Finding the packages for a source file" New topic
Author

Finding the packages for a source file

Alex Jacobsen
Greenhorn

Joined: Feb 01, 2005
Posts: 5
If I have the name for a source file as a string, and I want to find all the packages used by that source file, how would I go about doing it within the program? Assuming the source file is in the same directory as the program.
M Beck
Ranch Hand

Joined: Jan 14, 2005
Posts: 323
Originally posted by Alex Jacobsen:
If I have the name for a source file as a string, and I want to find all the packages used by that source file, how would I go about doing it within the program? Assuming the source file is in the same directory as the program.


all i can think of is to read the source file and scan for any "import" statements. it's kindof brute-force, and it won't pick up any packages used by the packages that the source file imports, but maybe it's a start at least...?
Alex Jacobsen
Greenhorn

Joined: Feb 01, 2005
Posts: 5
Thank you for the response. I was thinking of something similar, but was wondering if there was maybe something more sophisticated I was missing.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by M Beck:
all i can think of is to read the source file and scan for any "import" statements.
Also, remember that you don't have to import classes to use them. You'll also need to parse the source code for any fully-qualified class names throughout. Finally, while unlikely, a class can use "Class.forName("some.package.you.dont.know.about.MyClass");" It's a thorny problem for sure.

If the class is compiled, maybe you could load it using your own ClassLoader subclass that logs each Class that gets loaded. I'm not very familiar with this, but I believe that loads all related classes immediately -- not just when they are instantiated. This would also give you the full dependency list as the load should load all necessary classes recursively.

Again, that's my assumption. I've never tried it.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Finding the packages for a source file