How to write our own marker interface in Java?

  1. Serialization is handled by the ObjectInputStream and ObjectOutputStream classes. If a class has special serialization needs, the methods to create are outlined in the API. Reflection is used to invoke these methods.

  2. The same way you would write any other interface.

  3. There's nothing stopping you from putting methods in a marker interface.

The more common practice now is to use annotations to provide the same metadata marker interfaces provide.


Yes We can create our own Marker interface..See following one...

interface Marker{   
}

class MyException extends Exception {   
    public MyException(String s){
        super(s);
    }
}

class A  {
    void m1() throws MyException{        
         if((this instanceof Marker)){
             System.out.println("successfull");
         }
         else {
             throw new MyException("Must implement interface Marker ");
         }      
    }   
}

public class CustomMarkerInterfaceExample  extends A implements Marker
{ // if this class will not implement Marker, throw exception
    public static void main(String[] args)  {
        CustomMarkerInterfaceExample a= new CustomMarkerInterfaceExample();
        try {
            a.m1();
        } catch (MyException e) {

            System.out.println(e);
        }


    }

}

  • 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.