我希望能够像java.io.Serializable
或Cloneable
一样编写自己的标记接口,并让JVM能够理解。请建议我实现过程。
例如,我实现了一个名为NotInheritable
的接口,所有实现该接口的类都必须避免继承。
我希望能够像java.io.Serializable
或Cloneable
一样编写自己的标记接口,并让JVM能够理解。请建议我实现过程。
例如,我实现了一个名为NotInheritable
的接口,所有实现该接口的类都必须避免继承。
public interface MyMarkerInterface {}
public class MyMarkedClass implements MyMarkerInterface {}
然后你可以有一个只接受MyMarkerInterface
实例的方法:
public myMethod(MyMarkerInterface x) {}
或者在运行时使用instanceof
进行检查。
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);
}
}
}
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
}
}
}