在Java中有没有办法找到传递给函数的变量的名称? [英] Is there a way in Java to find the name of the variable that was passed to a function?

查看:236
本文介绍了在Java中有没有办法找到传递给函数的变量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为testForNull的Java函数

I have a Java function called testForNull

   public static void testForNull(Object obj)
    {
     if (obj == null)
      {
        System.out.println("Object is null");
      }
    }

我用它来测试多个对象以确保它们是不是空的。但是,我无法以这种方式告诉变量的名称。

I use it to test multiple objects to ensure they are not null. But, I am unable to tell the name of the variable that way.

例如。如果我说

    testForNull(x);
    testForNull(y);
    testForNull(z);

我无法分辨这三行中的哪一行导致Object is null输出。当然,我可以简单地在函数中添加另一个参数,例如

I cannot tell which of the three lines caused the "Object is null" output. Of course, I can simply add another parameter to the function and have something like

    testForNull(x, "x");
    testForNull(y, "y");
    testForNull(z, "z");

但是我想知道是否可以在不明确传递变量的情况下推断出变量的名称。谢谢。

But I want to know whether it is possible to deduce the name of the variable without passing it explicitly. Thanks.

推荐答案

考虑参数可能不是变量(因此没有名称):

Consider that the parameter might not have been a variable (and therefore wouldn't have a name):

testForNull(x != y);

这篇关于在Java中有没有办法找到传递给函数的变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆