How to get name of a Class in Java from within a static method | Fresher level java interview Question

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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.