需要打印函数在调用时使用的实际参数名称

时间:2015-06-10 11:05:56

标签: java performance swing reflection

我想在函数中打印函数实际参数名称。

供参考,请参阅下面的代码。我正在尝试反思。

class Refrction
{
    public static int a=12;
    public static int b=12;
    public static int c=13;

    public void click(int x)
    {
        Class cls=Refrction.class;
        Field[] fields = cls.getFields();               

        //here i want to print "a" if function actual parameter is "a" while calling the click function
        //here i want to print "b" if function actual parameter is "b" while calling the click function
        //here i want to print "c" if function actual parameter is "c" while calling the click function

    }
}


public class Reflections extends Refrction
{
    public static void main(String[] args)
    {
        Refrction ab=new Refrction();
        ab.click(a);
        ab.click(b);
        ab.click(c);
    }
}

1 个答案:

答案 0 :(得分:6)

除非abc的值永远不会改变(并且您可以通过查看值来推断出哪个变量被用作参数),否则这是不可能的。您需要将更多信息传递给该方法。

一种方法是做

public void click(int x, String identifier) {
    ...
}

并用

调用它
ab.click(a, "a");

或者,您可以将值包装在(可能是可变的)对象中,如下所示:

class IntWrapper {
    int value;
    public IntWrapper(int value) {
        this.value = value;
    }
}

然后再做

public static IntWrapper a = new IntWrapper(11);

public void click(IntWrapper wrapper) {
    if (wrapper == a) {
        ...
    }
    ...
}