📜  Java中的类 getModifiers() 方法和示例

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

Java中的类 getModifiers() 方法和示例

Java.lang.Class 类getModifiers()方法用于获取该类的Java语言修饰符。该方法返回一个整数,表示此类的编码修饰符。
句法:

public int getModifiers()

参数:此方法不接受任何参数。
返回值:此方法返回一个整数,表示该类的编码修饰符。
下面的程序演示了 getModifiers() 方法。
例子:

Java
// Java program to demonstrate getModifiers() method
 
import java.util.*;
import java.lang.reflect.*;
 
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
 
        System.out.println("Class represented by myClass: "
                           + myClass.toString());
 
        // Get the modifiers of myClass
        // using getModifiers() method
        System.out.println(
            "Modifiers of myClass: "
            + Modifier.toString(
                  myClass.getModifiers()));
    }
}


Java
// Java program to demonstrate getModifiers() method
 
import java.util.*;
import java.lang.reflect.*;
 
class Main {
 
    private class Arr {
    };
 
    public Object obj;
 
    Main()
    {
 
        obj = new Arr();
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        Main t = new Main();
 
        // returns the Class object
        Class myClass = t.obj.getClass();
 
        // Get the modifiers of myClass
        // using getModifiers() method
        System.out.println("Modifiers of myClass: "
                           + Modifier.toString(
                                 myClass.getModifiers()));
    }
}


输出:
Class represented by myClass: class Test
Modifiers of myClass: public

示例 2:

Java

// Java program to demonstrate getModifiers() method
 
import java.util.*;
import java.lang.reflect.*;
 
class Main {
 
    private class Arr {
    };
 
    public Object obj;
 
    Main()
    {
 
        obj = new Arr();
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        Main t = new Main();
 
        // returns the Class object
        Class myClass = t.obj.getClass();
 
        // Get the modifiers of myClass
        // using getModifiers() method
        System.out.println("Modifiers of myClass: "
                           + Modifier.toString(
                                 myClass.getModifiers()));
    }
}
输出:
Modifiers of myClass: private

参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getModifiers–