java - 将类类型作为参数传递

标签 java

我有两种这样的方法

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/

相关文章:

java - java中构建失败

java - Tomcat/TomEE 添加 "/localhost"到 servletContext.getResource ("myStaticFile")

java - Java 中的列表列表列表列表列表

java - 插入双向链表

java - 如何在运行时在 spring 中重新加载/刷新属性而不重新启动 jvm?

java - 如何使用JProgressBar和java来制作浏览器?

java - 使用文本文件中的数据作为 if 语句中的条件

java - 为什么 Integer.parseInt 方法不适用于分割字符串?

java - 如何整合Spring Boot、Camel和Mybatis

java - 'gracefully'如何处理Spring 3应用中的bean初始化失败?