Getting the class name from a static method in Jav

2019-01-02 19:56发布

How can one get the name of the class from a static method in that class. For example

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

To put it in context, I actually want to return the class name as part of a message in an exception.

标签: java static
15条回答
牵手、夕阳
2楼-- · 2019-01-02 20:01

This instruction works fine:

Thread.currentThread().getStackTrace()[1].getClassName();
查看更多
柔情千种
3楼-- · 2019-01-02 20:05

Abuse the SecurityManager

System.getSecurityManager().getClassContext()[0].getName();

Or, if not set, use an inner class that extends it (example below shamefully copied from Real's HowTo):

public static class CurrentClassGetter extends SecurityManager {
    public String getClassName() {
        return getClassContext()[1].getName(); 
    }
}
查看更多
只靠听说
4楼-- · 2019-01-02 20:06

If you are using reflection, you can get the Method object and then:

method.getDeclaringClass().getName()

To get the Method itself, you can probably use:

Class<?> c = Class.forName("class name");
Method  method = c.getDeclaredMethod ("method name", parameterTypes)
查看更多
何处买醉
5楼-- · 2019-01-02 20:07

In Java 7+ you can do this in static method/fields:

MethodHandles.lookup().lookupClass()
查看更多
不流泪的眼
6楼-- · 2019-01-02 20:11

Verbatim use of caller's class like MyClass.class.getName() actually does the job, but is prone to copy/paste errors if you propagate this code to numerous classes/subclasses where you need this class name.

And Tom Hawtin's recipe is in fact not bad, one just needs to cook it the right way :)

In case you have a base class with a static method that may be called from subclasses, and this static method needs to know the actual caller's class, this may be achieved like the following:

class BaseClass {
  static sharedStaticMethod (String callerClassName, Object... otherArgs) {
    useCallerClassNameAsYouWish (callerClassName);
    // and direct use of 'new Object() { }.getClass().getEnclosingClass().getName()'
    // instead of 'callerClassName' is not going to help here,
    // as it returns "BaseClass"
  }
}

class SubClass1 extends BaseClass {
  static someSubclassStaticMethod () {
    // this call of the shared method is prone to copy/paste errors
    sharedStaticMethod (SubClass1.class.getName(),
                        other_arguments);
    // and this call is safe to copy/paste
    sharedStaticMethod (new Object() { }.getClass().getEnclosingClass().getName(),
                        other_arguments);
  }
}
查看更多
流年柔荑漫光年
7楼-- · 2019-01-02 20:11

A refactoring-safe, cut&paste-safe solution that avoids the definition of ad-hoc classes below.

Write a static method that recover the class name having care to include the class name in the method name:

private static String getMyClassName(){
  return MyClass.class.getName();
}

then recall it in your static method:

public static void myMethod(){
  Tracer.debug(getMyClassName(), "message");
}

Refactoring safety is given by avoiding the use of strings, cut&paste safety is granted because if you cut&paste the caller method you won't find the getMyClassName() in the target "MyClass2" class, so you will be forced to redefine and update it.

查看更多
登录 后发表回答