gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:06:45 25 4
gpt4 key购买 nike

有没有办法比较 Object 中的属性是否等于字符串?

这是一个名为 Person 的示例对象

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") 具有与 Object(Person) 相同的属性名称。

最佳答案

你将使用反射:

http://java.sun.com/developer/technicalArticles/ALT/Reflection/

更准确地说,假设您知道对象的类别(Person),您将结合使用 Class.getField(propertyName) 来获取表示该属性的 Field 对象,并使用 Field.get(person) 来获取实际值(如果存在)。那么如果它不为空,你就会认为这个对象在这个属性中有值。

如果您的对象遵循一些约定,您可以使用“Java Beans”特定的库,例如:http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/package-summary.html#standard.basic

关于java - 如何将对象属性名称与字符串进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6123994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com