简体   繁体   English

如何在Java中使用字符串与字段名称进行比较?

[英]How to use string to compare with field names in java?

I have a class named MyClass. 我有一个名为MyClass的类。 It has many fields of type MyField. 它具有MyField类型的许多字段。 How do I return a reference to a particular field whose name matches a String's value? 如何返回对名称与字符串值匹配的特定字段的引用?

public class MyClass{
public MyField field1;
public MyField field2;
public MyField field3;

public MyField whichField(String nameOfField){
//e.g. String = "field3", then return field3
//of course I can do if else, but it will be tedious If I have long list of MyField fields, can I iterate over all field names, and return whose name matches?

}

}

edit 编辑

I tried reflection from the answers below, I create a temp placeholder, and I wish to reutrn it but, 我尝试从下面的答案中进行反思,我创建了一个临时占位符,但我希望保留它,但是,

MyField temp = MyClass.class.getDeclaredField(whichFieldString);

doesnt work, I get type mismatch, cant convert error 不起作用,我得到类型不匹配,无法转换错误

How do I cast this? 我该如何投放? How do I return this field? 如何返回此字段?

As an alternative: 作为备选:

If all fields are of the same type and are accessed by their field name (most of the time) you could avoid the hassle and brittleness of using reflection by utilizing a Map . 如果所有字段都属于同一类型并且可以通过它们的字段名称(大多数情况下)进行访问,则可以通过使用Map来避免使用反射的麻烦和脆弱性。

The map associates a key (in your case the "field name") with a value. 该映射将一个键(在您的情况下为“字段名称”)与一个值相关联。 Instead of an arbitrary number of fields, MyClass would look like: 代替任意数量的字段,MyClass看起来像:

public class MyClass {
   private final Map<String, MyField> fields = new HashMap<>();

   /* code to initially fill the map */

   public MyField whichField(String fieldName) {
      return fields.get(fieldName);
   }
}

You can do it easily with reflection 您可以轻松完成反射

Class<MyClass> clazz = MyClass.class;
Field requieredField = clazz.getDeclaredField("myFielldName");

EDIT 编辑

This solution is pertinent is the number of fields is fixed. 与该解决方案有关的是字段数是固定的。 As it was mentioned in comments and answers, if you want to store a dynamic number of values, then a Map (or a Collection if you only need to enumerate the values) is much more suitable. 正如注释和答案中提到的那样,如果要存储动态数量的值,则Map(或者Collection,如果只需要枚举值)则更合适。

You can do this with reflection. 您可以通过反射来做到这一点。 Class A has the fields we want to search through: A类具有我们要搜索的字段:

public class A {

    private String field1;
    private String field2;
    private String field3;

}

And B shows how to iterate over the fields declared in A, matching on a particular field name: B显示了如何遍历A中声明的字段,并与特定的字段名称匹配:

public class B {

    public B() {
        Field field = findFieldByName("field1");
        System.out.println(field);
    }

    private Field findFieldByName(String name) {
        Field[] fields = A.class.getDeclaredFields();
        for(Field f : fields) {
            if(f.getName().equals(name)) {
                return f;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        new B();
    }
}

You'll have to use reflection: 您必须使用反射:

import java.lang.reflect.Field;

public class MyClass {
    public MyField field1;
    public MyField field2;
    public MyField field3;

    public MyField whichField(String nameOfField) {
        MyField fieldName = null;
        Field[] fields = MyClass.class.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals(nameOfField)) {
                // Do whatever you want to do
            }
        }

        return null;
    }

}

class MyField {
}

您可能要使用一个集合,例如Map<String, MyField>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM