ace*_*ace 1 java compare object-property
有没有办法比较a中的属性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
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个方法需要检查该字符串是否与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]));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的实际问题远不是这个,现在我怎么知道我是否需要将字符串存储到该属性中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 .基本