【问题标题】:Compile error getting class with getClass()使用 getClass() 获取类时编译错误
【发布时间】:2013-04-11 13:43:45
【问题描述】:

我正在了解getClass 及其工作原理。

我读到: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

但我真的不明白为什么会失败:

boolean b;
Class c = b.getClass();

谁能向我解释为什么它给我一个错误?

【问题讨论】:

  • b.class 可能有效...

标签: java class boolean javadoc


【解决方案1】:

boolean b; 是原始数据类型,您不能使用 . 运算符对其调用方法,试试Boolean bBoolean 是原始 boolean 的包装类。

试试这个:

Boolean b = null;
Class c = b.getClass();

或者更好

Boolean b = null;
Class<? extends Boolean>  c = b.getClass();

【讨论】:

    【解决方案2】:

    您的变量bboolean 类型,这是一个原始类型。原始类型不是对象,因此您无法获取它们的类。

    【讨论】:

      【解决方案3】:

      因为booleans 不是对象。无法在 boolean 上调用任何方法

      【讨论】:

        【解决方案4】:

        b - 是 primite,你不能在它上面调用 getClass。它不是一个对象

        【讨论】:

          【解决方案5】:

          因为您使用的是原语boolean。对象Boolean不会发生这种情况

          【讨论】:

            【解决方案6】:

            您不能对原始数据类型调用 getClass() 方法。 这将为您解决问题

            Boolean b;//Change it to Boolean wrapper class
            Class c = b.getClass();
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-02-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-07-10
              • 2022-06-10
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多