how to get java class name

I am inside the method of some object, let's say

class A
  void f()


then I create object and call method f()
(new A).f();
inside method f() how can I get classname of the object as string?
So the code to do so in this case should return "A"
Who is Participating?
CEHJConnect With a Mentor Commented:
String className = getClass().getName();
amakalskiAuthor Commented:
Sorry, I forgot that method f() is static and I tried to use getClass().getName();
but compiler says that I cannot user non-static getClass() from within static method. Is there alternative for getClass() for static methods or in other words is it possible to get class descriptor from within static method without using 'ClassName'.class, because this static function I can move to another class without being tied to particular 'ClassName'
vaibhavmishra062201Connect With a Mentor Commented:
If you move this static method to another class, then it will be static method of that class, and it will print name of that class.
In any case, you will know the name of the class in which this static method resides.
sciuriwareConnect With a Mentor Commented:
There is a way to find all the class names that you passed calling methods:
            throw new Exception();
         catch(Exception e)
         StackTraceElement[] u = e.getStackTrace();

// Now u[0] describes the class you're in.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.