天天看点

Java中的标记接口

介绍

标记接口是没有变量和方法的接口(空接口),例如Serializable,Cloneable和Remote接口,这些接口都是标记接口

public interface Serializable 
{
  // nothing here
}
           

Cloneable接口

这个接口在java.lang包中。Object类中有clone()方法,当一个类实现Cloneable接口后,表示这个类可以进行合理的实体变量复制,如果没有实现该接口,当调用Object的clone方法时,会报 CloneNotSupportedException异常,通过实现该接口的类,要重写Object的clone方法。

// Java program to illustrate Cloneable interface 
import java.lang.Cloneable; 
  
// By implementing Cloneable interface 
// we make sure that instances of class A 
// can be cloned. 
class A implements Cloneable 
{ 
    int i; 
    String s; 
  
    // A class constructor 
    public A(int i,String s) 
    { 
        this.i = i; 
        this.s = s; 
    } 
  
    // Overriding clone() method 
    // by simply calling Object class 
    // clone() method. 
    @Override
    protected Object clone() 
    throws CloneNotSupportedException 
    { 
        return super.clone(); 
    } 
} 
  
public class Test 
{ 
    public static void main(String[] args) 
        throws CloneNotSupportedException 
    { 
        A a = new A(20, "GeeksForGeeks"); 
  
        // cloning 'a' and holding 
        // new cloned object reference in b 
  
        // down-casting as clone() return type is Object 
        A b = (A)a.clone(); 
  
        System.out.println(b.i); 
        System.out.println(b.s); 
    } 
} 
           

Serializable接口

这个接口在java.io包中,实现该接口,使得对象可以合理存储它的状态到文件中,即是序列化。没有实现该接口的类是不能进行序列化和反序列化的。

// Java program to illustrate Serializable interface 
import java.io.*; 
  
// By implementing Serializable interface 
// we make sure that state of instances of class A 
// can be saved in a file. 
class A implements Serializable 
{ 
    int i; 
    String s; 
  
    // A class constructor 
    public A(int i,String s) 
    { 
        this.i = i; 
        this.s = s; 
    } 
} 
  
public class Test 
{ 
    public static void main(String[] args) 
      throws IOException, ClassNotFoundException 
    { 
        A a = new A(20,"GeeksForGeeks"); 
  
        // Serializing 'a' 
        FileOutputStream fos = new FileOutputStream("xyz.txt"); 
        ObjectOutputStream oos = new ObjectOutputStream(fos); 
        oos.writeObject(a); 
  
        // De-serializing 'a' 
        FileInputStream fis = new FileInputStream("xyz.txt"); 
        ObjectInputStream ois = new ObjectInputStream(fis); 
        A b = (A)ois.readObject();//down-casting object 
  
        System.out.println(b.i+" "+b.s); 
  
        // closing streams 
        oos.close(); 
        ois.close(); 
    } 
} 
           

Remote 接口

这个接口是在java.rmi包中,实现该接口的类存储在一个机器上,可以由另一台机器进行访问,表示这个对象的方法可以由非本地的虚拟机进行调用。