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

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here.
    Kindly keep blogging. If anyone wants to become a Java developer learn from Java EE Online Training from India.
    or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete