Java LocationUtil-class And Method Code Example


Here is an example of how the LocationUtil class from the logback library can be used:

import ch.qos.logback.core.util.LocationUtil;

public class MyClass {
    public void myMethod() {
        StackTraceElement stackTraceElement = LocationUtil.getStackTraceElement(MyClass.class);
        System.out.println("Class name: " + stackTraceElement.getClassName());
        System.out.println("Method name: " + stackTraceElement.getMethodName());
        System.out.println("File name: " + stackTraceElement.getFileName());
        System.out.println("Line number: " + stackTraceElement.getLineNumber());
    }
}

In this example, MyClass uses an instance of LocationUtil to get the StackTraceElement of the current method. The getStackTraceElement method takes a Class object as an argument and returns the StackTraceElement of the first method on the stack trace that was called from a class whose name is equal to the fully-qualified name of the class passed as an argument.

You can also use classLocation to get the class location.

String location = LocationUtil.classLocation(MyClass.class);

This will return the location of the class file of the class "MyClass"

You can also use findFirst method to get the first stack trace element of a class.

StackTraceElement stackTraceElement = LocationUtil.findFirst(MyClass.class);

This will return the first stack trace element of the class "MyClass"

Please note that LocationUtil is a utility class and it does not have any constructor.