当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。