java.lang.NoSuchFieldError exception while the field is defined

只愿长相守 提交于 2019-12-24 10:19:03

问题


I'm working on a web application for Apache Tomcat. I'm using a class called Location in which i defined a field called ipAddresses. Here it is:

package com.maxmind.geoip;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

public class Location {
private final static double EARTH_DIAMETER = 2 * 6378.2;
private final static double PI = 3.14159265;
private final static double RAD_CONVERT = PI / 180;

public Set<String> ipAddresses;
public String countryCode;
public String countryName;
public String region;
public String city;
public String postalCode;
public float latitude;
public float longitude;
public int dma_code;
public int area_code;
public int metro_code;

public Location() {
    ipAddresses = new HashSet<String>();
}
...
}

However, after deploying the webapp to the server (war file) and trying to run the servlet that is using this class in it, i'm getting the exception java.lang.NoSuchFieldError for ipAddresses.

Moreover, when trying to debug it (Eclipse), when i reach a place where Location loc = new Location() is called, two weird things happen:

  1. The constructor i coded isn't called, the debugger won't step into it, instead the program counter arrow is shown on on of the imports of in the Location.java file.
  2. After "returning" from the Location loc = new Location() call, when i'm viewing the object's content the field actually does not exist.
  3. The source file that was deployed with the jar file does include this field.

I have tried many things:

  • cleaning and building the project and redeploying it.
  • cleaning the server's working directory, both manual and by using Eclipse.
  • changing the working directory of the server, in Eclipse.
  • re-installing the server in Eclipse.
  • re-installing Tomcat entirely, three times and to different locations!

I'm pretty stuck. What could it be?


回答1:


The symptoms indicate that you have the com.maxmind.geoip.Location class in some JAR in the JRE/lib or JRE/lib/ext or any other Eclipse/Tomcat-independent classpath location which will always have precedence in classloading over the WAR's classes.

Examining the loc.getClass().getProtectionDomain().getCodeSource().getLocation() after you construct it should give insights about where it is actually been loaded from.




回答2:


Are you using the field at all? Are there any references to it?. It is entirely possible that Eclipse is optimising it away.

In Windows->Preferences->Java->Compiler, there is a setting: Preserve unused (never read) local variables. Is this checked? If not, check it and try again.



来源:https://stackoverflow.com/questions/8183214/java-lang-nosuchfielderror-exception-while-the-field-is-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!