0

I have two methods like this

public void updateA (Object obj) throws CommonException
{
  if ( !(obj instanceof A) )
  {
     throw new CommonException(obj);
  }
  // other codes  
}


public void updateB (Object obj) throws CommonException
{
  if ( !(obj instanceof B) )
  {
     throw new CommonException(obj);
  }
  // other codes  
}

Now I want to extract the instance checking part into a separate method. Is it possible to do as follows?

public void chkInstance (Object obj, Class classType) throws CommonException
{
  if ( !(obj instanceof classType) )
  {
     throw new CommonException(obj);
  }
}
Fahim
  • 723
  • 1
  • 7
  • 11
  • You could also just attempt to cast it to the `classType` that you want it to be - if it's not an instance of one an exception will be thrown. It won't be a `CommonException`, it'll be a `ClassCastException`, but could you catch this in a higher order class? – Nate W. Nov 25 '11 at 05:56

1 Answers1

3

Use Class.isInstance:

if(!(classType.isInstance(obj)) {
    // ...
}

The documentation actually flat-out states (emphasis mine):

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
  • Thank you Martel. But how can I call this method? Like this? : chkInstance (obj, A.class); ? – Fahim Nov 25 '11 at 06:23