Can we write marker user interfaces

I want to write my own marker interfaces, such as java.io.Serializableor Cloneable, which the JVM can understand. Please suggest me the execution procedure.

For example, I implemented an interface called NotInheritable, and all classes implementing this interface should avoid inheritance.

+5
source share
5 answers
public interface MyMarkerInterface {}

public class MyMarkedClass implements MyMarkerInterface {}

Then you can, for example, have a method that accepts only an instance MyMarkerInterface:

public myMethod(MyMarkerInterface x) {}

or check the box instanceofat runtime.

+3
source

Yes We can write our own token exception ... see the following example ....

interface Marker{   
}

class MyException extends Exception {   

    public MyException(String s){
        super(s);
    }
}

class A implements Marker {

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

/* Class B has not implemented Maker interface .
 * will not work & print unsuccessful Must implement interface Marker
*/
class B extends A  {    


}

// Class C has not implemented Maker interface . Will work & print successful

public class C  extends A implements Marker   
 { // if this class will not implement Marker, throw exception
     public static void main(String[] args)  {
     C a= new C();
     B b = new B();

     try {
        a.m1(); // Calling m1() and will print
        b.m1();
     } catch (MyException e) {

        System.out.println(e);
    }

}
}

OUTOPUT

+2
source

, myMethod , MyInterface.

interface MyInterface{}

class MyException extends RuntimeException{

    public MyException(){}
    public MyException(String message){
        super(message);
    }
}

class MyClass implements MyInterface{
    public void myMethod(){
        if(!(this instanceOf MyInterface)){
            throw new MyException();
        }else{
            // DO YOUR WORK
        }
    }
}
+1

You can write your own token interface, the JVM knows nothing about it.

You must provide functionality using instanceof. check this

0
source

The token interface is an empty interface. This means that you just need to create an interface and not create any method in it. You will find the best explanation here .

This approach can be replaced by Annotations , which have similar functionality by type. more

-3
source

All Articles