So our class's static method must return the name. So consider this class and its static method:
So following are the methods:
Using reflections
If you want the entire package name with it, call:
If you only want the last element, call:
Using getEnclosingClass method
Abusing the security manager
OR using the static inner class method to return the class name:
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