How does a java compiler resolve a non-imported name

Posted by gexicide on Stack Overflow See other posts from Stack Overflow or by gexicide
Published on 2014-06-06T08:00:53Z Indexed on 2014/06/07 3:27 UTC
Read the original article Hit count: 144

Consider I use a type X in my java compilation unit from package foo.bar and X is not defined in the compilation unit itself nor is it directly imported. How does a java compiler resolve X now efficiently? There are a few possibilities where X could reside:

  1. X might be imported via a star import a.b.*
  2. X might reside in the same package as the compilation unit
  3. X might be a language type, i.e. reside in java.lang

The problem I see is especially (2.). Since X might be a package-private type, it is not even required that X resides in a compilation unit that is named X.java. Thus, the compiler must look into all entries of the class path and search for any classes in a package foo.bar, it then must read every class that is in package foo.bar to check whether X is included.

That sounds very expensive. Especially when I compile only a single file, the compiler has to read dozens of class files only to find a type X. If I use a lot of star imports, this procedure has to be repeated for a lot of types (although class files won't be read twice, of course).

So is it advisable to import also types from the same package to speed up the compilation process? Or is there a faster method for resolving an unimported type X which I was not able to find?

© Stack Overflow or respective owner

Related posts about java

Related posts about import