开发者

Get the method name and it's contained parameters by parsing the exception

开发者 https://www.devze.com 2023-02-02 02:10 出处:网络
When I received an exception such as IOException or RunTimeException, I can only know the line number in the class.

When I received an exception such as IOException or RunTimeException, I can only know the line number in the class.

开发者_如何学CFirst of my question. Is it possible to retrieve the method name through exception? Second, is it possible to retrieve the method and the parameter of this method by line number?

p.s. I need to know the exact method name and its parameters, because I want to distinguish the overloading methods. To distinguish overloading methods, all that I know is to determine its parameters.


try{
//your code here}
catch(Exception e){
  for (StackTraceElement st : e.getStackTrace())
  {
    System.out.println("Class: " + st.getClassName() + " Method : " 
                      +  st.getMethodName() + " line : " + st.getLineNumber());  
   }
}

as you can see in the code above, you can get the stackTrace and loop over it to get all the method names and line numbers, refer to this for more info http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StackTraceElement.html


If you look at the stacktrace you can know in which line the error occurred.

When using an overriden method you get the exact class name, source file and line number, you just have to know how to read it.

From that page:

 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)  //<--- HERE!!!!
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)

This says, the problem occurred in line 9 of file MyClass.java in the method mash, which was in turn invoked by the method crunch at line 6 of the same file which was invoked by main in line 3 of the same file.

Heres the source code:

 class MyClass {
     public static void main(String[] args) {
         crunch(null); // line 3
     }
     static void crunch(int[] a) {
         mash(a); // line 6 
     }
     static void mash(int[] b) {
         System.out.println(b[0]);//line 9, method mash.
     }
 }

Basically you just have to ... well read it!

Stacktraces are a bit hard to grasp the first time, but later they become a very powerful tool.

I hope this helps.


pass it the exception and it will print the parameter types of the methods along with the exception

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;

public class Main
{
    public static void main(String[]  args)
    {
        new Main().run();
    }
    public void run(){
        try
        {
            new Car().run(60, "Casino");
        }
        catch (Exception e)
        {
            detailedException(e);
        }
        try
        {
            new Engine().run(10);
        }
        catch (Exception e)
        {
            detailedException(e);
        }
    }
    public void detailedException(Exception e)
    {
        try
        {
            StringBuilder buffer = new StringBuilder(e.getClass().getName()).append(" \"").append(e.getMessage()).append("\"\n");
            for (var trace: e.getStackTrace())
            {
                buffer.append("\tat ").append(trace.getClassName()).append(".").append(trace.getMethodName()).append("(").append(trace.getFileName()).append(":").append(trace.getLineNumber()).append(")[");
                Class<?> clazz = Class.forName(trace.getClassName());
                ArrayList<Method> methods = new ArrayList<>(Arrays.asList(clazz.getMethods()));
                methods.removeIf(m -> !m.getName().equals(trace.getMethodName()));
                Method method = methods.get(0);
                for (var param: method.getParameters())
                {
                    buffer.append(param.getName()).append(":").append(param.getParameterizedType().getTypeName()).append(", ");
                }
                buffer.append("]->").append(method.getGenericReturnType().getTypeName()).append("\n");
            }
            System.err.println(buffer);
        }
        catch (Exception parseFailed){
            e.printStackTrace();
        }
    }
}
class Car extends Engine
{
    public void run(int when, String where) throws Exception 
    {
        super.run(25);
    }
}
class Engine
{
    public String run(int For) throws Exception 
    {
        throw new Exception("need more fuel");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消