In Java, it is a method to get the name of the class or method being executed. Since it uses only the standard library, you can copy and paste it immediately.
Example.java
public class Example {
public static void main(final String[] args) {
final String className = new Object(){}.getClass().getEnclosingClass().getName();
System.out.println(className);
}
}
output
Example
Example.java
public class Example {
public static void main(final String[] args) {
final String className = Thread.currentThread().getStackTrace()[1].getClassName();
System.out.println(className);
}
}
output
Example
Util.java
public class Util {
/**
*Gets the name of the running class.
* @return class name
*/
public static String getClassName() {
return Thread.currentThread().getStackTrace()[2].getClassName();
}
}
UtilTest.java
public class UtilTest {
public static void main(final String[] args) {
final String className = Util.getClassName();
System.out.println(className);
}
}
output
UtilTest
Example.java
public class Example {
public static void main(final String[] args) {
final String methodName = new Object(){}.getClass().getEnclosingMethod().getName();
System.out.println(methodName);
}
}
output
main
Example.java
public class Example {
public static void main(final String[] args) {
final String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(methodName);
}
}
output
main
Util.java
public class Util {
/**
*Gets the name of the method being executed.
* @return method name
*/
public static String getMethodName() {
return Thread.currentThread().getStackTrace()[2].getMethodName();
}
}
UtilTest.java
public class UtilTest {
public static void main(final String[] args) {
final String methodName = Util.getMethodName();
System.out.println(methodName);
}
}
output
main
Recommended Posts