I have following code in my application:
for(PropertyDescriptor property : myObjectProperties){
    if(property.getName().equals("myPropertyName")){
         // logic goes here
    }
}
This is of course hazardous on multiple levels, probably the worst being that if I rename the attribute "myPropertyName" on "MyObject", the code will break.
That said, what is the simplest way I could reference the name of the property without explicitly typing it out (as this would enable me to get compiler warning)? I'm looking something like:
for(PropertyDescriptor property : myObjectProperties){
    if(property.getName().equals(MyObject.myPropertyName.getPropertyName())){
         // logic goes here
    }
}
Or is this even possible with Java?
You can define target property, by adding some annotation to it. Then in a loop search fields that has desired annotation.
First define an annotation, that will be accessible at runtime
@Retention(RetentionPolicy.RUNTIME)
public @interface Target {
}
nice and easy, now create your class that uses it
public class PropertySearcher {
    int awesome;
    int cool;
    @Target
    int foo;
    int bar;
    String something;
}
now lets search for it
public static void main(String[] args) {
    PropertySearcher ps = new PropertySearcher();
    for (Field f : ps.getClass().getDeclaredFields()) {
        for (Annotation a : f.getDeclaredAnnotations()) {
            if (a.annotationType().getName().equals(Target.class.getName())) {
                System.out.println("Fname= " + f.toGenericString());
                //do magic here
            }
        }
    }
}
output
Fname= int reflection.PropertySearcher.foo
property found.
This way you can refactor your code with no worries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With