如果我知道值,如何从Java接口获取变量名?

时间:2022-07-25 23:11:02

I have a Java interface like this:

我有一个像这样的Java接口:

String User_Name= "username";
String User_Password="password";

Inside to a different class, I want to get the variable Name when I know the value. For example I know the "username" and I want to find in which variable this value is stored. I am expecting to get the User_Name. Is this possible with reflection?

在一个不同的类里面,我想知道值的时候得到变量Name。例如,我知道“用户名”,我想找到该值存储在哪个变量中。我希望得到User_Name。这可能与反思有关吗?

1 个解决方案

#1


1  

You can use reflection to iterate through all fields and check the values. This should serve as a basic example:

您可以使用反射迭代所有字段并检查值。这应该作为一个基本的例子:

for (Field field : obj.getClass().getDeclaredFields()) {
    if(field.get(obj) == desired_value)
           System.out.println("The matching field is " + field.getName());
    System.out.println(field.getName()
             + " - " + field.getType()
             + " - " + field.get(obj));

}

#1


1  

You can use reflection to iterate through all fields and check the values. This should serve as a basic example:

您可以使用反射迭代所有字段并检查值。这应该作为一个基本的例子:

for (Field field : obj.getClass().getDeclaredFields()) {
    if(field.get(obj) == desired_value)
           System.out.println("The matching field is " + field.getName());
    System.out.println(field.getName()
             + " - " + field.getType()
             + " - " + field.get(obj));

}