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);
}
}
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.