I want to write my own marker interfaces like java.io.Serializable
or Cloneable
which can be understandable to JVM. Please suggest me the implementation procedure.
For example I implemented a interface called NotInheritable
and all the classes implementing this interface has to avoid inheritance.
JDK Marker Interfaces Hence, the Cloneable marker interface is an indicator to the JVM that we can call the Object. clone() method. In the same way, when calling the ObjectOutputStream. writeObject() method, the JVM checks if the object implements the Serializable marker interface.
Instead of marker interface, Java 5 provides the annotations to achieve the same results. It allows flexible metadata capability. Therefore, by applying annotations to any class, we can perform specific action.
Marker Interfaces in Java have special significance because of the fact that they have no methods declared in them which means that the classes implementing these interfaces don't have to override any of the methods. A few of the marker interfaces already exist in the JDK like Serializable and Cloneable.
It seems annotation is a better choice than the marker interface as the same effect can be achieved by the annotations. It can mark variables, methods, and/or classes. It can mark any class specifically, or via inheritance. A marker interface will mark all subclasses of the marked class.
public interface MyMarkerInterface {}
public class MyMarkedClass implements MyMarkerInterface {}
Then you can for example have method taking only MyMarkerInterface
instance:
public myMethod(MyMarkerInterface x) {}
or check with instanceof
at runtime.
Yes We can write our own marker exception.... see 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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With