2011-05-25 214 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

相关问题