我有两种这样的方法
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);
}
}
最佳答案
使用Class.isInstance
:
if(!(classType.isInstance(obj)) {
// ...
}
documentation实际上是完全状态(强调我的):
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.
关于java - 将类类型作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8265241/