ghostrider
ghostrider

Reputation: 2238

imports of files missing in the class file

I am using certain static variables from another interface and hence I am importing this Interface in my class. However this import is not being seen in the .class file of my Java class. However other imports of non-static members are seen. Is this the expected behavior? If yes, then why?

Upvotes: 1

Views: 558

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308159

Imports are never encoded in .class files at all, they are purely syntactic sugar to avoid having to use full names for classes and/or members in your Java source code. The class file doesn't know if you used import package.AClass or just referred to package.AClass by its full name in your source file.

What you might be seeing is that no reference to your imported fields are found in your class at all, which might be due to one of two reasons:

  • you import the class/member but never actually reference it in the rest of your code.

    Due to the fact that imports are syntactic sugar, this means that no reference to the imported thing exists in your "real code"

  • you reference a static final field that contains a compile time constant in which case no reference to that field will be generated, but the value will be inlined directly.

    class A {
      public static final String CONSTANT = "foo";
    }
    
    class B {
      private String field = A.CONSTANT;
    }
    

    In this case the class file for B will contain the value "foo" and no reference to the class A.

Upvotes: 3

Related Questions