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)
.
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