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

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

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

Java.lang.Class 类的 getSimpleName ()方法用于获取该类的简单名称,如源代码中给出的。该方法以String的形式返回这个类的简单名称。如果此类是匿名的,则此方法返回空字符串。
句法:

public String getSimpleName()

参数:此方法不接受任何参数。
返回值:该方法以String的形式返回该类的简单名称。如果此类是匿名的,则此方法返回空字符串。
下面的程序演示了 getSimpleName() 方法。
示例 1:

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


Java
// Java program to demonstrate getSimpleName() method
 
import java.util.*;
 
class Main {
 
    public Object obj;
 
    Main()
    {
 
        class Arr {
        };
 
        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 simple name of myClass
        // using getSimpleName() method
        System.out.println("SimpleName of myClass: "
                           + myClass.getSimpleName());
    }
}


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

示例 2:

Java

// Java program to demonstrate getSimpleName() method
 
import java.util.*;
 
class Main {
 
    public Object obj;
 
    Main()
    {
 
        class Arr {
        };
 
        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 simple name of myClass
        // using getSimpleName() method
        System.out.println("SimpleName of myClass: "
                           + myClass.getSimpleName());
    }
}
输出:
SimpleName of myClass: Arr

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