4

I ran across an exception today and managed to eliminate the error. At first, let me give you an example code.

public class Foo () {
    protected String var;
}

public class Bar extends Foo () {
    public String isVarNull() {
        return (this.var == null);
    }
}

So these are my two example classes. Both classes are located in some jar. Everything works fine in this scenario (imageine they were usefull classes and are used in some productive enviroment). All I do now is change the type of Var in Foo to Integer.

public class Foo () {
    protected Integer var;
}

Afterwards I compiled class Foo and replaced the old Class-File in the Jar with the new one. When I try to access the field var now (in method isVarNull() of class Bar) I get this Exception:

Caused by: java.lang.NoSuchFieldError: test/Bar.var at test.Bar.isVarNull(Bar.java:6)

As far as I believe it has something to do with the bytecode of the class Bar. Do compiled classes "know" the type of a method/variable used in the code? In this case, does Bar "know", what type var should return and therefore throw an error, because the returning type of the method has changed? I would really appreciate a detailed answer!

Kind regards

Mr Smith
  • 3,318
  • 9
  • 47
  • 85
Christian Riese
  • 594
  • 1
  • 5
  • 18
  • 1
    "Do compiled classes "know" the type of a method/variable used in the code?" => Yes, Java is a type-safe language, also at runtime the type of variables is known (except for type erasure in generics). – Jesper Aug 11 '16 at 12:47

2 Answers2

4

I think the top answer here might help out: NoSuchFieldError Java

But to not depend on a link too much, the general idea is you likely only compiled Foo. As such, Foo's var type does get changed, but Bar's idea of what type var should be does not. So yes, compiled classes do "know" what type of method/variable they're referencing. In this case, Bar still thinks it's looking for a String named var in Foo, but since it can't find one, you're getting this error. Compiling both, I think, should get all your classes on the same page again.

Community
  • 1
  • 1
Lord Farquaad
  • 712
  • 1
  • 12
  • 33
2

You need to rebuild the solution containing all the classes.

Changes which has been made in base class isnt reflected in derived.

rebuilding your project should work.

Dheeraj Kumar
  • 3,917
  • 8
  • 43
  • 80