📜  Java中的类 getName() 方法及示例

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

Java中的类 getName() 方法及示例

Java.lang.Class 类getName()方法用于获取该实体的名称。该实体可以是类、数组、接口等。该方法将实体的名称作为字符串返回。
句法:

public String getName()

参数:此方法不接受任何参数。
返回值:此方法将实体的名称作为字符串返回。
下面的程序演示了 getName() 方法。
示例 1:

Java
// Java program to demonstrate getName() method
 
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 name of myClass
        // using getName() method
        System.out.println("Name of myClass: "
                           + myClass.getName());
    }
}


Java
// Java program to demonstrate getName() method
 
public class Test {
 
    class Arr {
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for A
        Class arrClass = Arr.class;
 
        // Get the name of arrClass
        // using getName() method
        System.out.println("Name of arrClass: "
                           + arrClass.getName());
    }
}


输出:
Class represented by myClass: class Test
Name of myClass: Test

示例 2:

Java

// Java program to demonstrate getName() method
 
public class Test {
 
    class Arr {
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
 
        // returns the Class object for A
        Class arrClass = Arr.class;
 
        // Get the name of arrClass
        // using getName() method
        System.out.println("Name of arrClass: "
                           + arrClass.getName());
    }
}
输出:
Name of arrClass: Test$Arr

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