Need to print function's actual parameter name used while calling

85 Views Asked by At

I want to print function actual parameter name in function.

For reference please refer below code.Here i am trying 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

There are 1 best solutions below

1
On BEST ANSWER

Unless the values of a, b and c never changes (and you can deduce which variable was used as argument by looking at the value) this is not possible. You need to pass more information to the method.

One way would be to do

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

and call it with

ab.click(a, "a");

Or, you could wrap the values in a (possibly mutable) object, as follows:

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

and then do

public static IntWrapper a = new IntWrapper(11);

and

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