如何将对象属性名称与字符串进行比较?

| 有没有一种方法可以比较“ 0”中的属性是否等于字符串? 这是一个名为
Person
的Objet示例
public class Person {

    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName){
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    //.... Getter and Setter

}
现在,我有一种方法需要检查该字符串是否与
Person
属性名称相同。
public boolean compareStringToPropertName(List<String> strs, String strToCompare){
    List<Person> persons = new ArrayList<Person>();
    String str = \"firstName\";

    // Now if the Person has a property equal to value of str, 
    // I will store that value to Person.
    for(String str : strs){

        //Parse the str to get the firstName and lastName
        String[] strA = str.split(delimeter); //This only an example

        if( the condintion if person has a property named strToCompare){
            persons.add(new Person(strA[0], strA[1]));
        }
    }

}
我的实际问题远非如此,现在我如何知道是否需要将字符串存储到
Object
的属性中。到目前为止,我的关键是我还有另一个与对象属性相同的字符串。 我不想编写一个硬代码,这就是为什么我试图达到这样的条件的原因。 总而言之,是否有办法知道此字符串
(\"firstName\")
具有与对象
(Person)
相同的属性名。     
已邀请:
您可以使用
getDeclaredFields()
获取所有声明的字段,然后将其与字符串进行比较 例如:
class Person {
    private String firstName;
    private String lastName;
    private int age;
    //accessor methods
}

Class clazz = Class.forName(\"com.jigar.stackoverflow.test.Person\");
for (Field f : clazz.getDeclaredFields()) {
      System.out.println(f.getName());
}
输出   名字   姓   年龄 或者 您还可以
getDeclaredField(name)
Returns:
the Field object for the specified field in this class
Throws:
NoSuchFieldException - if a field with the specified name is not found.
NullPointerException - if name is null
也可以看看 反思文章     
您将使用Reflection: http://java.sun.com/developer/technicalArticles/ALT/Reflection/ 更准确地说,假设您知道对象(人)的类,则可以使用Class.getField(propertyName)的组合来获取表示属性的Field对象,并使用Field.get(person)来获取实际值(如果存在)。然后,如果不为空,则将认为该对象在此属性中具有值。 如果您的对象遵循某些约定,则可以使用\“ Java Beans \”特定的库,例如:http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/package-summary.html #standard.basic     

要回复问题请先登录注册