为什么Java会引入一些没有定义方法的接口(interface)?例如 Cloneable
、Serializable
、Type
等等。
第二件事:在 Class.class
包中,有一个方法定义了 registerNatives()
没有正文,它是从静态 block 调用的,但是 Class.class
不是抽象的,而是 final
。为什么这样?
以及为什么 Java 需要一些没有主体的方法才能从静态 block 中调用。?
最佳答案
Why do Java introduces some interface which has no methods defined in it?
这叫做 Tagged or Marker interface .这些不用于任何用途或操作。这些方法用于标记或标记一个类。这样您就可以确定某个类是否是这些类的子类。
about the second question
如果你仔细看,你会发现声明是
private static native void registerNatives();
所以registerNatives
是一个本地方法。
那么什么是原生方法。如果你看到 this so question
The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.
Native methods are usually used to interface with system calls or libraries written in other programming languages.
所以这些方法是从本地代码加载的。所以你不需要声明方法的主体,但它们仍然不是抽象的,因为它们是从本地代码实现的。
关于java - 没有方法的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20878039/