获取自定义方法名称可以通过以下几种方式:
Method
类的getName()
方法来获取方法的名称。例如:import java.lang.reflect.Method;
public class MyClass {
public void myMethod() {
// 获取方法名称
String methodName = new Object(){}.getClass().getEnclosingMethod().getName();
System.out.println(methodName);
}
}
MethodReference
来获取方法的名称。例如:import java.util.function.Consumer;
public class MyClass {
public static void main(String[] args) {
Consumer<String> consumer = MyClass::myMethod;
String methodName = consumer.toString().split("::")[1];
System.out.println(methodName);
}
public static void myMethod(String s) {
// do something
}
}
public class MyClass {
public static void main(String[] args) {
myMethod();
}
public static void myMethod() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
String methodName = stackTrace[1].getMethodName();
System.out.println(methodName);
}
}
以上是获取自定义方法名称的几种常见方式。根据具体的使用场景和需求,选择合适的方式来获取方法名称。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云