Monday, April 18, 2011

Getting a class name from static method

So our class's static method must return the name. So consider this class and its static method:

public class MyClass {
    public static String getClassName() {
        String name = ????; // what goes here so the string "MyClass" is returned
        return name;
    }
}

So following are the methods:
Using reflections
MyClass.class.getName();
Also,
If you want the entire package name with it, call:
String name = MyClass.class.getCanonicalName();

If you only want the last element, call:
String name = MyClass.class.getSimpleName();

Using getEnclosingClass method
return new Object() { }.getClass().getEnclosingClass();

Abusing the security manager
System.getSecurityManager().getClassContext()[0].getName();

OR using the static inner class method to return the class name:
public static class CurrentClassGetter extends SecurityManager {
    public String getClassName() {
        return getClassContext()[1].getName(); 
    }
}



No comments:

Post a Comment

Chitika