Finding the name of a Class in Java from within a static method
One of our regular visitors (Ranvijay) had asked it a couple of days back. Though, the code is pretty straightforward, I think it might help few others if posted as an article.
One of the many possible ways of finding the name of the class in Java from within a static method is by using a static nested class, which will have a public instance method returning the class name of the enclosing class (in our case the class where we have the particular static method).
public class GetClassNameInStaticMethod {
public static void main(String[] args) {
// Calling a Static Method
System.out.println("Current Class Name: " + getCurClassName());
}
public static String getCurClassName(){
return (new CurClassNameGetter()).getClassName();
}
//Static Nested Class doing the trick
public static class CurClassNameGetter extends SecurityManager{
public String getClassName(){
return getClassContext()[1].getName();
}
}
}
Output
Current Class Name: GetClassNameInStaticMethod
Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.
2 comments:
Can u tell me , how can i create the
object of any class without help
of constructor
in the main method of the class
You would probably get the answer in this article - Ways of Creating Objects in Java. Let me know if this doesn't help.
Post a Comment