August 23, 2021

Custom Marker Interface Implementation in Java

Marker interface has no method. Java has built-in marker interface like Serializable, Cloneable & Event Listener 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.


Create the empty interface

interface Marker{    }

Write a class and implements the interface 

class A implements Marker {
  //do some task
}

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

Reference: 
https://stackoverflow.com/questions/11008033/how-to-write-our-own-marker-interface-in-java/35278304 
https://en.wikipedia.org/wiki/Marker_interface_pattern

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts