【问题标题】:Can't resolve method className()无法解析方法 className()
【发布时间】:2016-04-23 13:45:45
【问题描述】:

我不明白为什么这段代码有错误。有什么建议吗?

谢谢

public class HelloWorld {

  public static void main(String[] args) {

    int choice = 2;

    choice.className().getName();

  }
}

【问题讨论】:

  • 你能解释一下你要做什么吗?

标签: java classname


【解决方案1】:

您不能在原始类型上调用 className()

【讨论】:

  • 那么,我如何检查“选择”实际上是一个 int 吗?
  • 您可以使用 Integer.parseInt()。或者,如果您想使用类名,请改用包装器 (Integer) 和choice.getClass().getName()
【解决方案2】:

你不能,因为原语不是对象。

如果一个类的全名可用,则可以使用静态方法 Class.forName() 获取对应的 Class。这不能用于原始类型。

【讨论】:

    【解决方案3】:

    您无法像那样确定原始变量数据类型。 代码应该如下所示。

    public class HelloWorld {
      public static void main(String[] args) {
        int choice = 2;
        String type = ((Object)choice).getClass().getName();
      }
    }
    

    【讨论】:

      【解决方案4】:

      你不能,因为它是原始类型,但你可以使用 Integer 代替 并检查它是否属于您可以使用的特定对象

      Object temp = 1;
      if(temp  instanceof Integer){
       System.out.println("Integer Object");
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-15
        • 2015-06-10
        • 2019-08-28
        • 2019-10-10
        • 2019-06-13
        相关资源
        最近更新 更多