co.zohar co.zohar - 3 months ago 19
Java Question

java.lang.ClassCastException: Z cannot be cast to java.lang.String

I'm getting an error:

java.lang.ClassCastException: Z cannot be cast to java.lang.String
while trying to run coverage (EclEmma) on a Junit test. If I run the test regularly (without coverage) then it passes.

This is the code (all the fields in the class are
Strings
):

@Override
public Map<String, String> getErrors() throws IllegalAccessException, IllegalArgumentException {

Map<String, String> errors = new HashMap<String, String>();

for (Field field : this.getClass().getDeclaredFields()) {
field.setAccessible(true);
String value = (String) field.get(this);

if (value.equals("N")) {
if (!errors.containsKey(field.getName())) {
errors.put(field.getName(), value);
}
}
}
return errors;
}

Answer

Try to do this:

String value = "null";
if(field.get(this) != null)
    value = field.get(this).toString();

Instead of this:

String value = (String) field.get(this);
Comments