这个可以写一个Marker接口吗 [英] Is this possible to write a Marker interface

查看:52
本文介绍了这个可以写一个Marker接口吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经完成了以下教程:

I have gone through the following tutorial :

http://www.javaworld.com/community/node/2915

看完上面的文章后,我觉得这是不可能的写一个 Marker 接口,因为,你怎么能指示编译器,那个,什么标签,它嵌入到您的 Marker 界面的 .class 文件中.

And after reading the above article, I feel, that it is not possible to write a Marker interface, because, how can you instruct compiler, that, what tag, it embed in the .class file for your Marker interface.

如果我错了,请纠正我.干杯:)

Please correct me, if I am wrong. cheers :)

推荐答案

这里的标签是十六进制代码AC ED,它被添加到实现Serializable接口的那个类的.class文件中.所以,JVM 以一种特殊的方式处理这个类文件(可能是一些繁重的资源分配工作),因为这个类的实例可能会被序列化.对于普通类,它添加了 CA FE 十六进制.

here tag is hexa decimal code AC ED, which is added to the .class file of that class which implements Serializable interface. So, that JVM treats this class file in a special way (may be some heavy resource allocation work), because instance of this class might be serialized. For normal classes, it adds CA FE hex.

啊哈!!我理解你的困惑.

Aha!! I understand your confusion.

  • CA FE 字节码文件的幻数;即编译类时获得的文件.任何类的字节码文件都有这个幻数,无论它是可序列化的还是不可序列化的.

  • CA FE the magic number for a bytecode file; i.e. the file you get when you compile a class. The bytecode file for ANY class has this magic number, whether it is serializable or not serializable.

AC ED 是序列化 Java 对象文件的幻数;即您序列化某个可序列化类的实例的文件.

AC ED is the magic number a serialized Java object file; i.e. the file you serialize an instance of some serializable class.

您混淆了两个不同的概念(类和实例)及其各自的表示.

You are mixing up two different concepts (classes and instances) and their respective representations.

所以你的问题的答案是......当然你可以编写自己的标记界面!对于实现标记接口的类,编译器没有什么特别之处.

So the answer to your question is ... of course you can write your own marker interfaces! There is nothing special to the compiler about a class that implements a marker interface.

然而,在纯 Java 中复制 Java 对象反序列化的实现是不可能的.对象反序列化使用后门(Unsafe.allocateInstance 方法)来创建对象而不调用它们的构造函数.AFAIK,无法从普通 Java 代码调用此方法.(即使可以,也不应该……)

However, it would be impossible to duplicate the implementation of Java object deserialization in pure Java. Object deserialization uses a backdoor (the Unsafe.allocateInstance method) to create objects without invoking their constructors. AFAIK, this method cannot be called from normal Java code. (And even if it can, it shouldn't be ...)

这篇关于这个可以写一个Marker接口吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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