How to write Custom Marker Interface ?

Marker Interface are simple Java interface having no methods or fields in it. Any empty Interface is called as marker interface which is generally used for identification purpose.

 

 

In JDK there are known Marker Interface are Serializable, Cloanable and Remote . Which are used to give indication to JVM or Compiler to perform something specific.

Let’s suppose I want to make a Marker Interface to identify Object which can be saved to database (can be persist).

1
2
3
4
5
public interface Persistable{

// This is my custom interface which will be used as marker interface.

}

Now I have two Entity classes EmployeeEntity and EmployeeDTO ,where EmployeeEntity can be saved in database and  EmployeeDTO should not be saved.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class EmployeeEntity implements Persistable,IEmployee{

//add some members

}

 

public class EmployeeDTO  implements IEmployee{

//add some members

}

 

public class SaveServiceTes{

 

public static void main(String... doYourBest) {

EmployeeEntity e = new EmployeeEntity(...)// with some properties

EmployeeDTO ed = new EmployeeDTO(...); //populate some properties

saveEmp(e);

saveEmp(ed);

}

 

public static void saveEmp(IEmployee emp){

//now before saving it to database

if((emp instanceof Persistable){

// save it to database

}else{

//throw some exception

}

}

}

 

Now whenever You will go to save any instance of Employee it will check if this instance is Persistable or not.If given instance is Persistable the You can save it to DB else You can throw some exception saying that this instance can not be saved to database.

Hope above example is suitable to make you understand the functionality of marker interface and how to use them as per our requirement.

 

Please share your suggestion/feedback in below comments.

Read Marker Interface vs Annotations in Java

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *