我有两种方法这样传类类型作为参数
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
}
现在我要提取的实例检查部分到一个单独的方法。 有没有可能做到以下几点?
public void chkInstance (Object obj, Class classType) throws CommonException
{
if (!(obj instanceof classType))
{
throw new CommonException(obj);
}
}
您也可以尝试将其转换为您想要的classType类型 - 如果它不是一个实例,则会引发异常。它不会是一个'CommonException',它会是一个'ClassCastException',但是你可以在更高级的类中捕获这个吗? –