Friday, 26 February 2010

Finding the name of a Class in Java from within a static method

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