我想编写自己的标记接口,如java.io.Serializable
或Cloneable
,这对JVM来说是可以理解的。请建议我实施程序。
例如,我实现了一个名为NotInheritable
的接口,实现此接口的所有类都必须避免继承。
答案 0 :(得分:3)
public interface MyMarkerInterface {}
public class MyMarkedClass implements MyMarkerInterface {}
然后,您可以使用仅采用MyMarkerInterface
实例的方法:
public myMethod(MyMarkerInterface x) {}
或在运行时与instanceof
核对。
答案 1 :(得分: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);
}
}
}
答案 2 :(得分: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
}
}
}
答案 3 :(得分:0)
您可以编写自己的Marker界面,JVM对此一无所知。
您必须使用instanceof
提供功能。 check this
答案 4 :(得分:-3)
标记接口是空接口。这意味着您只需要创建一个接口,而不是在其中创建任何方法。更好的解释,你会发现here。
此方法可以替换为具有类似功能的Annotations。 more