How to print the class, package and method name using java code

Below java code will be able to print the current java class name, package name as well as method name.

package com.java.amzi;

public class FindClassPackageName {

    public void className() {
        System.out.println("Class name is: " + this.getClass().getSimpleName());
    }

    public void packageName() {
        System.out.println("Package name is: "
                + this.getClass().getCanonicalName());
        // System.out.println(this.getClass().getName());
    }

    public void methodName() {
        System.out.println("Current method name is: "
                + new Exception().getStackTrace()[0].getMethodName());
    }

    public static void main(String[] args) {

        FindClassPackageName find = new FindClassPackageName();
        find.className();
        find.packageName();
        find.methodName();
    }
}


Output:

Class name is: FindClassPackageName
Package name is: com.java.amzi.FindClassPackageName
Current method name is: methodName

No comments:

Post a Comment