Passing a class type as a parameter

I have two methods like

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 verification part into a separate method. Can the following be done?

public void chkInstance (Object obj, Class classType) throws CommonException
{
  if ( !(obj instanceof classType) )
  {
     throw new CommonException(obj);
  }
}
0
source share
1 answer

Use Class.isInstance:

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

the documentation actually aligns the states (my highlight):

Determines whether the specified object is compatible with the object represented by this class. This method is the dynamic equivalent of a Java language instance statement .

+3
source

All Articles