2011-05-25 260 views
1

有沒有辦法比較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)

回答

4

可以使用getDeclaredFields()獲取所有聲明的字段,然後用繩子cmopare它


例如:

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()); 
} 

輸出

的firstName
lastName的
年齡


或者

您還可以getDelcatedField(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 

參見

5

你會使用反思:

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

更確切地說,假設你知道類對象(人)的,你可以使用Class.getField(propertyName的)的組合,以獲得表示屬性的Field對象,以及Field.get(person)以獲取實際值(如果存在)。那麼如果它不是空白的,你會認爲該對象在這個屬性中有一個值。

如果你的對象如下的一些約定,你可以使用「Java組件」特異性librariries,對於爲例:http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/package-summary.html#standard.basic

相關問題