5

Im using the following code that the fieldValue can have simple property , there is a way to check before im doing this code if fieldValue is not contain object that cannot be cast to string ?to avoid dump

keyVal.put(fieldName, (String) fieldValue);
James Berners
  • 103
  • 2
  • 11

3 Answers3

10
if (fieldValue instanceof String)
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I cannot use ti since field value is type object and can have there either numbers so the if will not success – James Berners Jun 10 '13 at 17:10
  • @James Berners: By type object, are you talking about `Class` type? If so, then you can use `asSubclass()` function to convert it into String class or use `isAssignableFrom()` to check if its a super-class of String. – keelar Jun 10 '13 at 17:17
  • @fge I have tried it I for example I got type object and there is value like 10 and the if is not work – James Berners Jun 10 '13 at 17:21
  • If by "not work" you mean evaluate to `false` then that is to be expected, since `Integer` cannot be cast to `String`. – arshajii Jun 10 '13 at 17:23
  • @JamesBerners: if what you need is a string representation of an Object, then my answer might be a fit for you. – keelar Jun 10 '13 at 17:56
2

Since String is a final class (and hence cannot have subclasses), I would consider using getClass over instanceof:

if (fieldValue != null && fieldValue.getClass() == String.class)
arshajii
  • 127,459
  • 24
  • 238
  • 287
1
if (fieldValue instanceof String) {

    keyVal.put(fieldName, (String) fieldValue);

}
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136