列出 Java 中一個類實現的介面


可以使用 java.lang.Class.getInterfaces() 方法來確定由物件表示的類實現的介面。此方法返回由類實現的所有介面的陣列。

演示此方法的程式如下 −

示例

 Live Demo

package Test;
import java.lang.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      listInterfaces(String.class);
   }
   public static void listInterfaces(Class c) {
      System.out.println("The Class is: " + c.getName());
      Class[] interfaces = c.getInterfaces();
      System.out.println("The Interfaces are: " + Arrays.asList(interfaces));
   }
}

輸出

The Class is: java.lang.String
The Interfaces are: [interface java.io.Serializable, interface java.lang.Comparable, interface java.lang.CharSequence]

現在讓我們瞭解一下上面的程式。

在方法 main() 中使用 String.class 呼叫方法 listInterfaces()。演示此方法的程式碼片段如下 −

listInterfaces(String.class);

在方法 listInterfaces() 中,使用 getName() 方法列印類的名稱。然後使用 getInterfaces() 方法返回由類實現的所有介面的陣列。然後使用 Arrays.asList() 列印此陣列。演示此方法的程式碼片段如下 −

System.out.println("The Class is: " + c.getName());
Class[] interfaces = c.getInterfaces();
System.out.println("The Interfaces are: " + Arrays.asList(interfaces));

更新於:2020 年 6 月 25 日

581 次瀏覽

開啟你的 職業生涯

完成課程取得認證

開始
廣告
© . All rights reserved.