Christian Riese Christian Riese - 3 months ago 11
Java Question

java.lang.NoSuchFieldError after changing class

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

Answer

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.