有沒有辦法比較Object
中的屬性是否等於一個字符串?如何將對象屬性名稱與字符串進行比較?
下面是一個簡單的Objet名爲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")
有一個相同的屬性名稱對象(Person)
。