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?
then how it is handled by the JVM for the classes which implements this marker interface?
Instances of class implementing a Java marker interface benefit from a specific behavior because some JDK classes or the HotSpot JVM provide a specific behavior for them.
For example take the Serializable
interface.
If you dig into ObjectOutputStream
and ObjectInputStream
you can see that the serialization/unserialization behavior are implemented in.
Here is a snippet of ObjectOutputStream.writeObject0() invoking by ObjectOutputStream.writeObject()
that illustrates that :
public class ObjectOutputStream extends OutputStream implements ObjectOutput, ObjectStreamConstants {
...
private void writeObject0(Object obj, boolean unshared) throws IOException {
...
if (obj instanceof String) {
writeString((String) obj, unshared);
} else if (cl.isArray()) {
writeArray(obj, desc, unshared);
} else if (obj instanceof Enum) {
writeEnum((Enum>) obj, desc, unshared);
} else if (obj instanceof Serializable) {
writeOrdinaryObject(obj, desc, unshared);
} else {
if (extendedDebugInfo) {
throw new NotSerializableException(
cl.getName() + "\n" + debugInfoStack.toString());
} else {
throw new NotSerializableException(cl.getName());
}
}
...
}
}
For the Cloneable
interface, look at the Object.clone()
method and you will see that it refers a native method that applies the Cloneable
specification.
In the HotSpot source code, the src\share\vm\prims\jvm.cpp, you can find the Object.clone()
implementation :
JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
JVMWrapper("JVM_Clone");
Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
const KlassHandle klass (THREAD, obj->klass());
JvmtiVMObjectAllocEventCollector oam;
// I skip all the processing that you can read in the actual source file
...
return JNIHandles::make_local(env, oop(new_obj));
JVM_END
For this marker interface the behavior is not directly implemented in a JDK class but by the JVM itself but the general idea is the same.
Can we create any new marker interfaces ?
If you create your own marker interfaces, you should do as the JVM and the JDK classes do to handle built-in instances of class implementing a Java marker interface : that is adding code to handle specifically the instances of your marker interfaces.
The very good answer of Adamski
shows the general idea to do that.