天天看點

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包中,實作該接口的類存儲在一個機器上,可以由另一台機器進行通路,表示這個對象的方法可以由非本地的虛拟機進行調用。