Reputation: 1624
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.
Upvotes: 7
Views: 17630
Reputation: 1391
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);
}
}
}
Upvotes: 2
Reputation: 11
suppose myMethod should be called only if marker MyInterface should be marked there.
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
}
}
}
Upvotes: 1
Reputation: 200158
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.
Upvotes: 3
Reputation: 8530
You can write your own Marker interface ,JVM do not know anything about it.
You have to provide functionality by using instanceof
. check this
Upvotes: 0
Reputation: 30865
A marker interface is an empty interface. This mean you just need to create a interface and do not create any method in it. Better explanation you will find here.
This approach can be replaced with Annotations that have similar functionality over types. more
Upvotes: -3