This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How to get Class Name Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to get Class Name" Watch "How to get Class Name" New topic
Author

How to get Class Name

jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 580
HI all

I have a Class ,inside that,how I get the name of the class.

For Ex:

class abc
{

// Here I need to get the name of the class.

}
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24190
    
  34

In an instance method, "this.getClass().getName()" will do it. In a static method, you really can't except using some pretty ugly and unreliable tricks using stack traces.


[Jess in Action][AskingGoodQuestions]
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 20080
    
  30

But you know which class you are in - it's static so it only belongs to the class in which it is coded. Therefore, you know it's class "abc". And if you know it's class "abc", you can get the Class object using "abc.class". So the name can be retrieved using "abc.class.getName()".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: How to get Class Name
 
jQuery in Action, 3rd edition