Question

Is there a way to compare if the property in an Object is equal to a string?

Here is a sample Objet named 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

}

Now I have a method that I need to check if that string is same with the Person property name.

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

}

My actual problem is far from this, for now how will I know if I need to store the string to a property of the Object. My key as of now is I have another string that same with the property of the object.

I don't want to have a hard code that's why I'm trying to achieve a condition like this.

To summary, Is there a way to know that this string("firstName") has an equal property name to Object(Person).

Was it helpful?

Solution

You can fetch all the declared fields using getDeclaredFields() , and then compare it with string


For example:

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

output

firstName
lastName
age


Alternatively

You can also getDeclaredField(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

See Also

OTHER TIPS

You'll use Reflection :

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

More precisely, assuming you know the class of the object (Person), you would use a combination of Class.getField(propertyName), to obtain a Field object that represent the property, and Field.get(person) to get the actual value (if it exists). Then if it is not blank, you would considered that the object has a value in this property.

If your objects follows some conventions, you can use "Java Beans" -specific librariries, for exemple : http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/package-summary.html#standard.basic

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top