how to get the name of method in current class
Hello in my java class Toto, I have 3 static methods I would like to know when I'm in one of these methods , how to get and display the name of package.class.methode in the try catch bloc ? I tried in methodeA:
public static void methodeA(){
try{
system.out.println("I do something");
}
catch(Exception e){
system.out.println("failed" +e.g开发者_JAVA百科etClass().getMethods().toString());
}
but it is not working, how also could I show it in try ? thanks
e.printStackTrace();
e.getStackTrace()[0].getMethodName();
e.printStackTrace();
- that will print the whole exception stracktrace - i.e. all the methods + line numbers.
e.getStackTrace()[0].getMethodName()
You can use the example below:
public class A
{
public static void main(String args[])
{
new A().intermediate();
}
void intermediate()
{
new A().exceptionGenerator();
}
void exceptionGenerator()
{
try
{
throw new Exception("Stack which list all calling methods and classes");
}
catch( Exception e )
{
System.out.println( "Class is :" + e.getStackTrace()[1].getClassName() +
"Method is :" + e.getStackTrace()[1].getMethodName());
System.out.println("Second level caller details:");
System.out.println( "Class is :" + e.getStackTrace()[2].getClassName() +
"Method is :" + e.getStackTrace()[2].getMethodName());
}
}
}
Have ou noticed you already have the information in your exception's stacktrace ?
Indeed, Exception class provides a getStackTrace()
method that returns you an array of StacktraceElement. Each of these elements gives you class name, method name, and some other details. What you can do is look in this array if you find one of your three methods, and voila !
However, be warned that detection of method name may fail if you use an obfuscator on your code.
The preferred option.....
catch(Exception e) {
e.printStackTrace();
}
or (not a wise option since you don't know what exception is thrown an you have no Stack Trace Elements printed).
catch(Exception e) {
System.out.println(e.getStackTrace()[0].getMethodName());
}
If you throw the exception, is affecting your performance. Is not needed throw the exception,
public class AppMain {
public static void main(String[] args) {
new AppMain().execute();
}
private void execute(){
RuntimeException exception = new RuntimeException();
StackTraceElement currentElement = exception.getStackTrace()[0];
System.out.println(currentElement.getClassName());
System.out.println(currentElement.getMethodName());
}
}
精彩评论