我们可以编写自定义标记接口

我想编写自己的标记接口,如java.io.SerializableCloneable ,这对JVM来说是可以理解的。 请建议我实施程序。

例如,我实现了一个名为NotInheritable的接口,实现此接口的所有类都必须避免inheritance。

 public interface MyMarkerInterface {} public class MyMarkedClass implements MyMarkerInterface {} 

然后,您可以使用例如仅采用MyMarkerInterface实例的方法:

 public myMethod(MyMarkerInterface x) {} 

或者在运行时检查instanceof

是的我们可以编写自己的标记exception….请参阅以下示例….

 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

假设只有在那里标记MyInterface时才应调用myMethod。

 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 } } } 

你可以编写自己的Marker接口,JVM对此一无所知。

您必须使用instanceof提供function。 检查一下

标记接口是空接口。 这意味着您只需要创建一个接口,而不是在其中创建任何方法。 你会在这里找到更好的解释。

此方法可以替换为具有与类型相似的function的注释 。 更多