Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding the packages for a source file  RSS feed

 
Alex Jacobsen
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 323
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 can't take it! You are too smart for me! Here is the tiny ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!