如何让JVM了解Java中的自定义标记接口 [英] How to let JVM know about custom marker interface in java

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

问题描述

是否可以用Java编写我们自己的标记接口.我正在写类似

Is that possible to write our own marker interface in java. I am writing a code like

public interface MyMarker {

}

这是标记界面吗?

如果可能的话,如何让JVM知道该接口是我自己创建的标记器接口?

If it is possible then how can I let JVM know that this interface is my own created marker interface?

推荐答案

是的,这是一个标记接口.您可以像以下这样简单地测试对象是否实现"了它:

Yes, that's a marker interface. You would test whether an object "implemented" it as simply as:

if (x instanceof MyMarker)

对于特定的(而不是对象)

For a particular class (instead of object) you'd want

if (MyMarker.isAssignableFrom(otherClass))

您应该考虑使用注释而不是标记界面.它们并不总是直接替代,但在许多情况下,它们用于相同的目标,并且注记(IMO)更干净.

You should consider using annotations instead of marker interfaces though. They're not always direct replacements, but in many cases they're used for the same goals, and annotations are (IMO) cleaner.

这篇关于如何让JVM了解Java中的自定义标记接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆