简体   繁体   中英

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?

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.

It's not possible to get the declared names of fields from an object as multiple fields can equal the same object. Its explained better here: Is it possible to get the declaration name of an object at runtime in java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM