-2

来说明对比。看下面的java片段:

public class Janerio {
    public static void main(String[] args) {
        new Janerio().enemy();
    }

    public static void enemy() {
        System.out.println("Launch an attack");
    }
}

上面的代码工作得很好,似乎是对这个问题的回答,因为输出如下所示。

Launch an attack

但是在下一刻,当我运行以下代码段时

public class Janerio {
    public static void main(String[] args) {
        System.out.println(new Janerio().class);
    }
}

我得到编译时错误

/Janerio.java:3: error: <identifier> expected
System.out.println(new Janerio().class);}
                                 ^
/Janerio.java:3: error: ';' expected
    System.out.println(new Janerio().class);}
                                          ^
2 errors

我不明白为什么会出现这种情况,因为在前面的代码片段中,我能够在类实例的帮助下访问静态“敌人”函数,但这里证明是错误的。我的意思是为什么我不能在类实例的帮助下访问“.class”静态方法。将“.class”视为Janerio类的静态函数或成员是错误的吗?与两个片段的静态特征类似是错误的吗?但是,一旦我用类名调用“.class”,事情似乎就是“.class”本质上是静态的,但是在使用类的实例调用“.class”时它会偏离静态。

public class Janerio {
    public static void main(String[] args) {
        System.out.println(Janerio.class);
    }
}

我们得到的输出:

class Janerio
4

4 回答 4

1

.class引用表示给定类的 Class 对象。当没有类的实例变量时使用它。因此它不适用于您的使用

在此处阅读更多信息: https ://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2

于 2017-11-23T15:50:42.073 回答
0

Yes, you can access these static members of classes that way, but the better practise is to use name of that class instead of the name of specific referece to object of that class. It makes your code clearer to understand and to read as static members of class do not belong to specific object but to whole class. For example:

class MyClass {
    static int count = 0;
}

It is better to access this field that way:

MyClass.field = 128;

instead of changing that value using the name of specific reference, for example:

MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.field = 128;

Because it can be confusing when you realize that this way even obj2.field has assigned new value of 128. It might look a bit tricky, so again, I would suggest the first presented method of calling methods or changing values assigned to fields.

于 2017-11-23T16:04:17.843 回答
0

将“.class”视为Janerio类的静态函数或成员我错了吗?

是的,它不是变量,也绝对不是方法。当您想要获取实例的类时,您必须使用 Object#getClass 方法。

于 2017-11-23T15:52:32.410 回答
0

.class您不选择字段(除了class是关键字)。

它是一个伪操作,可与类名一起使用,产生一个 Class 实例:

int.class, Integer.class, java.util.List.class
于 2017-11-23T15:51:38.507 回答