【问题标题】:How to check type of param class?如何检查参数类的类型?
【发布时间】:2012-04-04 06:47:06
【问题描述】:

我有以下方法:

public static String getServiceUri(Class<?> c) {

 // I'd like to check which type the parameter is...
 if(c.getClass().equals(MyClass.class)){
     do stuff 1
 } else {
     do stuff 2
 }
}

调用方法: getServiceUri(MyClass.class);

getServiceUri 上,我想根据ServiceClass 的类型调用WebService。

我知道 equals 会比较对象实例,但在这种情况下,我试图发现对象的类型。

有谁知道我可以用这种方法进行比较吗?

【问题讨论】:

    标签: java android instanceof


    【解决方案1】:
    instanceof operator is the best choice..
    

    你可以这样做

    if(c instanceof MyClass){
     //do your stuff
    
    }
    

    【讨论】:

    • instaceof 比像提问者那样匹配类要好得多。 instanceof 将继承考虑在内。
    • 我希望 SO 允许您修复一个字母,例如上面 instanceOf 中的大写 O。
    【解决方案2】:
    public static String getServiceUri(Class<?> classParam) {
    
        if(classParam instanceof MyClass){
    
         } 
    }
    

    这是错误的。它甚至无法编译,因为 classParam 需要是一个实际的实例(对象)才能使用 instanceof 运算符:因此得名。

    如果你想知道classParam是否完全等于MyClass.class:

    public static String getServiceUri(Class<?> c) {
    
        if(classParam == MyClass.class){
        }
    }
    

    但是,如果您想根据 MyClass 检查 classParam 的整个层次结构,那么您可以执行 classParam.isAssignableFrom(MyClass.class)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 2018-02-10
      • 1970-01-01
      • 2012-11-18
      • 2023-03-17
      • 1970-01-01
      • 2013-10-13
      相关资源
      最近更新 更多