java class name to string

java class name to string

To get the name of a Java class as a string, you can use the getName method of the Class class.

Here's an example of how to use the getName method to get the name of a Java class as a string:

refer to:‮uttual‬ri.com
public class Main {
  public static void main(String[] args) {
    Class<?> cls = Main.class;
    String className = cls.getName();
    System.out.println(className);  // Outputs: "Main"
  }
}

In this example, the getName method is called on the Class object representing the Main class. The method returns the name of the class as a string, which is "Main" in this case.

You can use a similar approach to get the name of any other class, by using the Class object representing that class. For example, to get the name of the String class:

Class<?> cls = String.class;
String className = cls.getName();
System.out.println(className);  // Outputs: "java.lang.String"

Note that the getName method returns the fully qualified name of the class, including the package name. If you only want the simple name of the class (without the package name), you can use the getSimpleName method instead.

For example:

Class<?> cls = Main.class;
String simpleName = cls.getSimpleName();
System.out.println(simpleName);  // Outputs: "Main"
Created Time:2017-11-03 00:14:50  Author:lautturi