【问题标题】:can we write custom marker interfaces我们可以编写自定义标记接口吗
【发布时间】:2012-05-20 01:41:13
【问题描述】:

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

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

【问题讨论】:

  • understandable to JVM 是什么意思?
  • 否,但 JVM 支持docs.oracle.com/javase/tutorial/java/IandI/final.html 将类标记为“不可继承”。
  • 答案是否定的,如果你想创建任何标记“重要接口”,那么你不能创建。但是,如果您想创建标记接口只是为了检查类对象是否是该标记接口的对象,那么可以。要创建标记接口“JVM 可理解”,jvm 需要自定义,我不确定是否可以完成。

标签: java


【解决方案1】:
public interface MyMarkerInterface {}

public class MyMarkedClass implements MyMarkerInterface {}

然后你可以例如让方法只采用MyMarkerInterface 实例:

public myMethod(MyMarkerInterface x) {}

或在运行时与instanceof 联系。

【讨论】:

    【解决方案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);
        }
    
    }
    }
    

    【讨论】:

    • 这个例子似乎毫无意义。为什么不让 Aa 类实现标记接口?
    【解决方案3】:

    假设只有当标记 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
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      你可以自己写Marker接口,JVM什么都不懂。

      您必须使用instanceof 提供功能。 check this

      【讨论】:

        【解决方案5】:

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

        这种方法可以用Annotations 代替,它们在类型上具有相似的功能。 more

        【讨论】:

        • 制造商还是有自己的重要性的。
        猜你喜欢
        • 2012-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多