-3

I have Object which can be double or long. How I can check whether type it have?

I have tried cast Object to double but if Object is long, error will occur (and vice versa for long).

ErgoAsh
  • 3
  • 1
  • 4
    `double` and `long` aren't objects; do you mean `Double` and `Long`? – Oliver Charlesworth Jun 14 '14 at 17:21
  • Note that what happens on a failed cast is not an "error", but an exception that can be caught. Do not assume you cannot do something just because you want to continue processing after an exception it can throw. I do agree that instanceof is better for class checks. – Patricia Shanahan Jun 14 '14 at 18:27

2 Answers2

1
if (yourObject instanceof Double) { } 
if (yourObject instanceof Long) { } 
Emanuel
  • 8,027
  • 2
  • 37
  • 56
0

You should use instanceof:

if (obj instanceof double) {
   // code
}

if(obj instanceof long) {
   // code
}

In this way you can check at runtime which type your object is.

FlashBack
  • 21
  • 8