Reputation: 152
how to create your own marker interface in java.how to notify the JVM to treat as special class? Can any one elaborate it.
Thanks in advance....
Upvotes: 3
Views: 682
Reputation: 306
Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface.
Example of market interface are Serializable, Clonnable and Remote interface.
Marker interface is used as a tag to pass a message to java compiler so that it can add special behavior to the class that implementing it.
You can create our own marker interface.
1) Cheque.java
public interface Cheque {
}
2) BankDraft.java
public interface BankDraft {
}
3)Payment.java
public class Payment implements BankDraft{
public void paymentByCheque() {
System.out.println("Payment By Cheque");
}
public void paymentByBankDraft() {
System.out.println("Payment by Draft");
}
}
4) MainClass.java
public class MainClass {
public static void main(String[] args) {
Payment p = new Payment();
if (p instanceof Cheque) {
p.paymentByCheque();
}
if (p instanceof BankDraft) {
p.paymentByBankDraft ();
}
}
}
In above example, I have created two empty interfaces Cheque and BankDraft. And Payment class implemented BankDraft interface. In MainClass class both interface behave as tag, output of MainClass depends on what interface you have implemented in Payment class.
Hope this will help.
Upvotes: 0
Reputation: 597086
You can't do anything like that with the JVM.
Well, you can, but you rarely want to do it. JVM agents can be 'plugged' in the JVM.
But marker interfaces are not used for that - they are used to mark classes that are eligible for something. Serializable
for example is not checked in the JVM - it is checked by the ObjectOutputStream
.
So you can create public interface MyMarker {}
and use instanceof
to verify whether a given class implements it, in your own logic.
However, since Java 1.5, the preferred way to do this is via an annotation (even if you use a jvm agent) -
public @interface MyMarker {..}
@MyMarker
public class MyClass { .. }
and then verify:
object.getClass().isAnnotationPresent(MyMarker.class);
Upvotes: 6