我们可以在Java中该类的实例变量的帮助下访问类的静态成员和静态功能



以说明对比度。查看以下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 name things thing that that" .class"本质上是静态的,但它偏离了与班级实例的打电话给" .class"。

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

输出我们得到:

class Janerio

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

在这里阅读更多:https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2

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

这是一个伪操作,可用于类名称,产生类实例:

int.class, Integer.class, java.util.List.class

我错误地考虑" .class"成为静态功能或类的成员Janerio?

是的,这不是变量,绝对不是一种方法。要获得实例的类时,您必须使用对象#getClass方法。

是的,您可以以这种方式访问类的这些静态成员,但是更好的做法是使用该类的名称,而不是对该类对象的特定介绍的名称。它使您的代码更加清晰地理解和阅读为类的静态成员,而不是属于特定对象,而是整个班级。例如:

class MyClass {
    static int count = 0;
}

最好以这种方式访问此字段:

MyClass.field = 128;

而不是使用特定参考的名称更改该值,例如:

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

因为当您意识到这种方式即使obj2.field分配了128个新值时,它可能会令人困惑。它看起来可能有些棘手,因此,再次提出了第一个介绍的调用方法或更改值分配给字段的值的方法。

最新更新