📜  方法类 | Java中的 isDefault() 方法

📅  最后修改于: 2022-05-13 01:55:08.481000             🧑  作者: Mango

方法类 | Java中的 isDefault() 方法

Java.lang.reflect.Method.isDefault()方法用于检查 Method 对象的方法是否为 Default Method: 或不是。如果方法对象是默认方法,则返回 true,否则返回 false。

默认方法:在接口类型中声明主体的公共非抽象静态方法。

句法:

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 Java