Java 類 getGenericInterfaces() 方法



描述

Java 類 getGenericInterfaces() 方法返回表示此物件所表示的類或介面直接實現的介面的型別。

宣告

以下是 java.lang.Class.getGenericInterfaces() 方法的宣告

public Type[] getGenericInterfaces()

引數

返回值

此方法返回此類實現的介面陣列。

異常

  • GenericSignatureFormatError − 如果泛型類簽名不符合 Java 虛擬機器規範第 3 版中指定的格式。

  • TypeNotPresentException − 如果任何泛型超介面引用不存在的型別宣告

  • MalformedParameterizedTypeException − 如果任何泛型超介面引用無法出於任何原因例項化的引數化型別。

沒有介面的類的泛型介面示例

以下示例顯示了 java.lang.Class.getGenericInterfaces() 方法的使用。在此程式中,我們建立了 ClassDemo 的例項,然後使用 getClass() 方法檢索例項的類。使用 getGenericInterfaces(),我們檢索了所有介面(如果已實現),否則列印備用訊息。

package com.tutorialspoint;

import java.lang.reflect.Type;

public class ClassDemo {

   public static void main(String []args) {         

      ClassDemo d = new ClassDemo();
      Class c = d.getClass();

      Type[] t = c.getGenericInterfaces();
      if(t.length != 0) {
         for(Type val : t) {
            System.out.println(val.toString());
         }
      } else {
         System.out.println("Interfaces are not implemented...");
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Interfaces are not implemented...

實現介面的類的泛型介面示例

以下示例顯示了 java.lang.Class.getGenericInterfaces() 方法的使用。在此程式中,我們建立了 ClassDemo 的例項,然後使用 getClass() 方法檢索例項的類。使用 getGenericInterfaces(),我們檢索了所有介面(如果已實現),否則列印備用訊息。

package com.tutorialspoint;

import java.lang.reflect.Type;

interface Print {
   public void show();
}

public class ClassDemo implements Print {

   public void show(){
      System.out.println("Class Demo");
   }
   
   public static void main(String []args) {         

      ClassDemo d = new ClassDemo();
      Class c = d.getClass();

      Type[] t = c.getGenericInterfaces();
      if(t.length != 0) {
         for(Type val : t) {
            System.out.println(val.toString());
         }
      } else {
         System.out.println("Interfaces are not implemented...");
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

interface com.tutorialspoint.Print

ArrayList 的泛型介面示例

以下示例顯示了 java.lang.Class.getGenericInterfaces() 方法的使用。在此程式中,我們使用了 ArrayList 的類。使用 getGenericInterfaces(),我們檢索了所有已實現的介面。

package com.tutorialspoint;

import java.lang.reflect.Type;
import java.util.ArrayList;

public class ClassDemo {

   public static void main(String []args) {         

      Class c = ArrayList.class;

      Type[] t = c.getGenericInterfaces();
      if(t.length != 0) {
         for(Type val : t) {
            System.out.println(val.toString());
         }
      } else {
         System.out.println("Interfaces are not implemented...");
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

java.util.List<E>
interface java.util.RandomAccess
interface java.lang.Cloneable
interface java.io.Serializable
java_lang_class.htm
廣告