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

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

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

Java.lang.Class 类getDeclaredClasses()方法用于获取该类的类,即私有、公有、受保护或默认的类及其成员,而不是继承的类。该方法以 Class 对象数组的形式返回该类的类。
句法:

public Class[] getDeclaredClasses()
               throws SecurityException

参数:此方法不接受任何参数。
返回值:该方法以Class对象数组的形式返回该类的
异常如果存在安全管理器并且不满足安全条件,则此方法将引发SecurityException
下面的程序演示了 getDeclaredClasses() 方法。
示例 1:

Java
// Java program to demonstrate
// getDeclaredClasses() method
 
import java.util.*;
 
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 classes of myClass
        // using getDeclaredClasses() method
        System.out.println(
            "DeclaredClasses of myClass: "
            + Arrays.toString(
                  myClass.getDeclaredClasses()));
    }
}


Java
// Java program to demonstrate
// getDeclaredClasses() method
 
import java.util.*;
 
class Main {
 
    private class Arr {
    };
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // returns the Class object for this class
        Class myClass = Class.forName("Main");
 
        System.out.println("Class represented by myClass: "
                           + myClass.toString());
 
        // Get the classes of myClass
        // using getDeclaredClasses() method
        System.out.println(
            "DeclaredClasses of myClass: "
            + Arrays.toString(
                  myClass.getDeclaredClasses()));
    }
}


输出:
Class represented by myClass: class Test
DeclaredClasses of myClass: []

示例 2:

Java

// Java program to demonstrate
// getDeclaredClasses() method
 
import java.util.*;
 
class Main {
 
    private class Arr {
    };
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // returns the Class object for this class
        Class myClass = Class.forName("Main");
 
        System.out.println("Class represented by myClass: "
                           + myClass.toString());
 
        // Get the classes of myClass
        // using getDeclaredClasses() method
        System.out.println(
            "DeclaredClasses of myClass: "
            + Arrays.toString(
                  myClass.getDeclaredClasses()));
    }
}
输出:
Class represented by myClass: class Main
DeclaredClasses of myClass: [class Main$Arr]

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