Nec*_*vil 2 java reflection performance swing
我想在函数中打印函数实际参数名.
供参考,请参考下面的代码.这里我正在尝试反思.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
除非值a
,b
并且c
永远不会改变(你可以推断出变量是通过观察值作为参数),这是不可能的.您需要将更多信息传递给该方法.
一种方法是做
public void click(int x, String identifier) {
...
}
Run Code Online (Sandbox Code Playgroud)
并称之为
ab.click(a, "a");
Run Code Online (Sandbox Code Playgroud)
或者,您可以将值包装在(可能是可变的)对象中,如下所示:
class IntWrapper {
int value;
public IntWrapper(int value) {
this.value = value;
}
}
Run Code Online (Sandbox Code Playgroud)
然后呢
public static IntWrapper a = new IntWrapper(11);
Run Code Online (Sandbox Code Playgroud)
和
public void click(IntWrapper wrapper) {
if (wrapper == a) {
...
}
...
}
Run Code Online (Sandbox Code Playgroud)