How to write our own marker interface in Java?

58,553

Solution 1

  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.

Solution 2

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

Solution 3

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);
        }


    }

}

Solution 4

Marker interface has no method. Java has built-in marker interface like Serializable, Clonable & EventListner etc that are understand by JVM.

We can create our own marker interface, but it has nothing to do with JVM, we can add some checks with instanceOf.

  1. Create the empty interface

    interface Marker{    }
    
  2. Write a class and implements the interface

    class A implements Marker {
        //do some task
    }
    
  3. Main class to check the marker interface instanceof

    class Main {
        public static void main(String[] args) {
            A ob = new A(){
            if (ob instanceof A) {
                // do some task
            }
        }
    }
    

Solution 5

As explained very nicely in the Wikipedia article Marker interface pattern, a marker interface is a form of metadata. Client code can test whether an object is an instance of the marker interface and adapt its (the client's) behavior accordingly. Here's a marker interface:

public interface CoolObject {
}

Then code can test whether an object is a CoolObject and do something with it:

if (anObject instanceof CoolObject) {
    addToCoolList((CoolObject) anObject);
}

The Serializable interface is defined as part of the Java language. You cannot implement behavior at that level yourself.

You can add methods to a marker interface, but that mixes the marker pattern with other conceptual uses for interfaces and can be confusing. (Is a class implementing the interface for the purposes of marking it, or for its behavior, or both?)

As explained in the Wikipedia article, marker interfaces in Java can (and probably should) be replaced with annotations.

Share:
58,553
Saravanan
Author by

Saravanan

I am Saravanan MCA Graduate.I am working as a Senior Developer in java environment. Email:[email protected]

Updated on July 09, 2022

Comments

  • Saravanan
    Saravanan almost 2 years

    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.

  • Saravanan
    Saravanan almost 12 years
    :thank you very much...i would like to know in which place they are writing code for relating ObjectInputStream class...?then only i can write my own marker interface like serilizable...
  • Premraj
    Premraj almost 12 years
    Go through the source of mentioned classes instead of asking exact lines!!
  • Jeffrey
    Jeffrey almost 12 years
    @Saravanan The JDK is open source. ObjectInputStream. ObjectOutputStream.
  • Freak
    Freak almost 11 years
    @Jeffrey nice answer :) but +1 for the comment The JDK is open source ;) :p
  • Ankit Sharma
    Ankit Sharma over 9 years
    This must b the answer
  • Tom
    Tom about 8 years
    You might want to pay more attention, when you write code, because your code for point 3 has several mistakes.
  • Diana
    Diana about 6 years
    nice explanation :)
  • sofs1
    sofs1 over 5 years
    "The more common practice now is to use annotations to provide the same metadata marker interfaces provide." - Marker interfaces define a type that is implemented by instances of the marked class; marker annotations do not. Source: Effective Java 3rd edition Item 41.