Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid magic strings in Java reflection

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?

like image 258
Jukka Hämäläinen Avatar asked Sep 30 '22 18:09

Jukka Hämäläinen


1 Answers

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.

like image 137
T.G Avatar answered Oct 09 '22 20:10

T.G