Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取方法名称及其';s通过分析异常包含参数_Java_Exception Handling - Fatal编程技术网

Java 获取方法名称及其';s通过分析异常包含参数

Java 获取方法名称及其';s通过分析异常包含参数,java,exception-handling,Java,Exception Handling,当我收到一个异常,例如IOException或RunTimeException,我只能知道类中的行号 我的第一个问题。是否可以通过异常检索方法名? 第二,是否可以通过行号检索该方法和该方法的参数 p、 我需要知道确切的方法名及其参数,因为我想区分重载方法。为了区分重载方法,我只知道确定它的参数 try{ //your code here} catch(Exception e){ for (StackTraceElement st : e.getStackTrace()) { Sy

当我收到一个异常,例如
IOException
RunTimeException
,我只能知道类中的行号

我的第一个问题。是否可以通过异常检索方法名? 第二,是否可以通过行号检索该方法和该方法的参数

p、 我需要知道确切的方法名及其参数,因为我想区分重载方法。为了区分重载方法,我只知道确定它的参数

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

正如您在上面的代码中所看到的,您可以获取stackTrace并在其上循环以获取所有的方法名称和行号,有关更多信息,请参阅此,如果查看stackTrace,您可以知道错误发生在哪一行

当使用重写方法时,您只需获得准确的类名、源文件和行号即可

从该页:

 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)  //<--- HERE!!!!
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
基本上你只需要。。。读得好

Stacktraces第一次有点难掌握,但后来它们变成了一个非常强大的工具


我希望这会有所帮助。

将异常传递给它,它将打印方法的参数类型以及异常

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");
    }
}
import java.lang.reflect.Method;
导入java.util.ArrayList;
导入java.util.array;
公共班机
{
公共静态void main(字符串[]args)
{
新建Main().run();
}
公开募捐{
尝试
{
新车().跑步(60,“赌场”);
}
捕获(例外e)
{
详细例外情况(e);
}
尝试
{
新发动机()。运行(10);
}
捕获(例外e)
{
详细例外情况(e);
}
}
公共无效详细例外(例外e)
{
尝试
{
StringBuilder缓冲区=新的StringBuilder(e.getClass().getName()).append(“\”).append(e.getMessage()).append(“\”\n”);
for(变量跟踪: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方法=新的ArrayList(Arrays.asList(clazz.getMethods());
方法.removeIf(m->!m.getName().equals(trace.getMethodName());
Method=methods.get(0);
for(var-param:method.getParameters())
{
append(param.getName()).append(“:”).append(param.getParameterizedType().getTypeName()).append(“,”);
}
append(方法.getGenericReturnType().getTypeName()).append(“\n”);
}
系统错误打印项次(缓冲区);
}
捕获(异常解析失败){
e、 printStackTrace();
}
}
}
高级轿车发动机
{
公共void运行(int-when,String-where)引发异常
{
超级跑(25);
}
}
类引擎
{
公共字符串运行(int For)引发异常
{
抛出新异常(“需要更多燃料”);
}
}

感谢您提供的代码。虽然我的问题是获取方法及其参数。我需要这两种方法,因为当方法重载时,我们必须通过它的参数来判断确切的方法。你不能从行号中知道吗?对Amjad Masad:你如何通过行号来区分重载方法?你可以区分行号调用了哪个重载方法。除非您在同一行上声明了多个方法(我不建议您这样做),或者源代码在编译时没有调试信息:-/To Peter:是的,我可以通过行号来区分。但我想知道如何编写代码来获取这些信息,而不是手动查找或跟踪。谢谢你,OscarRyz。我关心的不是重写方法,而是重载方法。例如:公共无效方法a(INTA);公共无效方法a(bool a);当然,我们可以根据给定的信息阅读源代码。我真正想做的是自动检索方法,使用代码捕获方法。你有什么办法吗?谢谢。对于重载的方法也应该如此。无法从stacktrace捕获方法参数。你能做的就是在抛出异常之前提供这些信息,我认为这是不可行的。你打算怎么处理这些信息?我很好奇我的想法是从抛出的异常方法中收集注释。如果方法没有重载,我至少可以知道方法名。但是,如果有重载方法,我无法判断哪一个方法抛出异常。我能得到的只是行号和类名,我们在下面讨论过。你有更好的主意吗,奥斯卡里斯?不管怎样,谢谢你的回复。
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");
    }
}