當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Method類 isDefault()用法及代碼示例


java.lang.reflect.Method.isDefault()方法用於檢查Method對象的方法是否為Default Method :。如果方法對象是默認方法,則返回true,否則將返回false。

默認方法:公共非抽象on-static方法,其主體以接口類型聲明。

用法:



public boolean isDefault()

返回值:此方法返回一個布爾值。如果方法對象是JVM規範的默認方法,則返回true,否則返回false。

以下示例程序旨在說明Method類的isDefault()方法:

範例1:

/* 
* Program Demonstrate isDefault() method  
* of Method Class. 
*/
import java.lang.reflect.Method; 
public class GFG { 
  
    // create main method 
    public static void main(String args[]) 
    { 
  
        try { 
  
            // create class object for interface Shape 
            Class c = Shape.class; 
  
            // get list of Method object 
            Method[] methods = c.getMethods(); 
  
            // print Default Methods 
            for (Method m:methods) { 
  
                // check whether the method is Default Method or not 
                if (m.isDefault()) 
                    // Print 
                    System.out.println("Method:"
                                       + m.getName() 
                                       + " is Default Method"); 
            } 
        } 
        catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
  
    private interface Shape { 
    default int
        draw() 
        { 
            return 0; 
        } 
  
        void paint(); 
    } 
}
輸出:
Method:draw is Default Method

範例2:

/* 
* Program Demonstrate isDefault() method  
* of Method Class. 
* This program checks all default method in Comparator interface 
*/
import java.lang.reflect.Method; 
import java.util.Comparator; 
public class Main6 { 
  
    // create main method 
    public static void main(String args[]) 
    { 
  
        try { 
  
            // create class object for Interface Comparator 
            Class c = Comparator.class; 
  
            // get list of Method object 
            Method[] methods = c.getMethods(); 
  
            System.out.println("Default Methods of Comparator Interface"); 
            for (Method method:methods) { 
                // check whether method is Default Method or not 
                if (method.isDefault()) 
                    // print Method name 
                    System.out.println(method.getName()); 
            } 
        } 
        catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}
輸出:
Default Methods of Comparator Interface
reversed
thenComparing
thenComparing
thenComparing
thenComparingInt
thenComparingLong
thenComparingDouble

參考:
https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#isDefault-




相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Method Class | isDefault() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。