Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write our own marker interface in Java?

I know marker interface in java. It is used to define a specific behaviour about a class. For example, Serializable interface has the specific ability to store an object into byte stream and its reverse process. But I don't know where this specific behaviour is implemented, because it doesn't have any method in it.

  1. How JVM invoke this specific behaviour?
  2. How to write our own marker interface? Can you give me a simple user defined marker interface for my understanding?
  3. Is it possible to have methods in marker interface?

Please guide me to resolve this issue.

like image 454
Saravanan Avatar asked Jun 13 '12 03:06

Saravanan


People also ask

Can I create my own marker interface in Java?

You can create your own custom marker interface in Java. Here is an example using custom Marker interface in Java. As we know marker interfaces define a type, that can be used with instanceof operator to test whether object is an instance of the specified type.

Can you declare your own marker interface?

Can we create custom marker interface? Of course you can write a marker interface. A marker interface is generally just a Interface with no methods at all (so any class could implement it).

Why do we create marker interface in Java?

Marker interface is used as a tag that inform the Java compiler by a message so that it can add some special behavior to the class implementing it.

What is marker interface example?

It is an empty interface (no field or methods). Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces.


1 Answers

  • How JVM invoke this specific behavior

ObjectOutputStream and ObjectInputStream will check your class whether or not it implementes Serializable, Externalizable. If yes it will continue or else will thrown NonSerializableException.

  • How to write our own marker interface

Create an interface without any method and that is your marker interface.

Sample

public interface IMarkerEntity {


}

If any class which implement this interface will be taken as database entity by your application.

Sample Code:

public boolean save(Object object) throws InvalidEntityException {
   if(!(object instanceof IMarkerEntity)) {
       throw new InvalidEntityException("Invalid Entity Found, cannot proceed");
   } 
   database.save(object);
}
  • Is this possible to have methods in marker interface?

The whole idea of Marker Interface Pattern is to provide a mean to say "yes I am something" and then system will proceed with the default process, like when you mark your class as Serialzable it just tells that this class can be converted to bytes.

like image 195
mprabhat Avatar answered Sep 28 '22 09:09

mprabhat