Java - get the current class name?

To get the current class name in Java, you can use the getClass() method of the Object class, which returns a Class object that represents the runtime class of the object.

Here is an example of how to get the current class name in Java:

public class Main {
  public static void main(String[] args) {
    String className = Main.class.getName();
    System.out.println(className);  // Outputs "Main"
  }
}

This code gets the Class object for the Main class using the .class notation and then calls the getName() method to get the name of the class as a String.

If you want to get the class name of an object at runtime, you can use the getClass() method of the object. For example:

public class Main {
  public static void main(String[] args) {
    Main main = new Main();
    String className = main.getClass().getName();
    System.out.println(className);  // Outputs "Main"
  }
}

This code creates an instance of the Main class and gets its Class object using the getClass() method. It then calls the getName() method to get the name of the class as a String.

It is important to note that the getName() method returns the fully qualified name of the class, including the package name. If you want to get only the simple name of the class (i.e., the name without the package), you can use the getSimpleName() method of the Class class. For example:

String simpleName = main.getClass().getSimpleName();
System.out.println(simpleName);  // Outputs "Main"