本文介绍了JVM如何处理标记接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Marker界面没有任何东西。它只包含接口声明,然后由JVM如何处理实现此标记接口的类?

Marker interface doesn't has any thing. It contains only interface declarations, then how it is handled by the JVM for the classes which implements this marker interface?

我们可以创建任何新的标记接口吗?

Can we create any new marker interfaces ?

推荐答案

您的问题应该是编译器如何处理标记接口,答案是:与其他任何接口没有区别。例如,假设我声明了一个新的标记接口 Foo

Your question should really be how does the compiler handle marker interfaces, and the answer is: No differently from any other interface. For example, suppose I declare a new marker interface Foo:

public interface Foo {
}

...然后声明一个类 Bar 实现 Foo

... and then declare a class Bar that implements Foo:

public class Bar implements Foo {
  private final int i;

  public Bar(int i) { this.i = i; }
}

我现在能够引用 Bar 通过类型 Foo 的引用:

I am now able to refer to an instance of Bar through a reference of type Foo:

Foo foo = new Bar(5);

...并检查(在运行时)对象是否实现 Foo

... and also check (at runtime) whether an object implements Foo:

if (o instanceof Foo) {
  System.err.println("It's a Foo!");
}

后一种情况通常是使用标记接口的驱动因素;前一种情况几乎没有什么好处,因为没有方法可以在 Foo 上调用(没有先尝试向下投射)。

This latter case is typically the driver behind using marker interfaces; the former case offers little benefit as there are no methods that can be called on Foo (without first attempting a downcast).

这篇关于JVM如何处理标记接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:32