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
Friday, 26 February 2010
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment