7

我想编写自己的标记接口,例如JVM 可以理解的java.io.Serializable或。Cloneable请建议我执行程序。

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

4

5 回答 5

3
public interface MyMarkerInterface {}

public class MyMarkedClass implements MyMarkerInterface {}

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

public myMethod(MyMarkerInterface x) {}

instanceof在运行时检查。

于 2012-05-11T12:52:52.517 回答
2

是的,我们可以编写自己的标记异常......请参见以下示例......

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

}
}

输出

于 2014-03-02T09:26:14.903 回答
1

假设只有当标记 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
        }
    }
}
于 2013-05-26T13:38:10.177 回答
0

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

您必须通过使用来提供功能instanceof检查这个

于 2012-05-11T12:59:34.590 回答
-3

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

这种方法可以用在类型上具有相似功能的注释代替。更多的

于 2012-05-11T12:54:02.830 回答