如何避免Java反射中的神奇字符串

如何避免Java反射中的神奇字符串,java,reflection,Java,Reflection,我的应用程序中有以下代码: for(PropertyDescriptor property : myObjectProperties){ if(property.getName().equals("myPropertyName")){ // logic goes here } } 当然,这在多个级别上都是危险的,可能最糟糕的是,如果我在“MyObject”上重命名属性“myPropertyName”,代码就会中断 也就是说,在不显式键入属性名称的情况下引用属性

我的应用程序中有以下代码:

for(PropertyDescriptor property : myObjectProperties){
    if(property.getName().equals("myPropertyName")){
         // logic goes here
    }
}
当然,这在多个级别上都是危险的,可能最糟糕的是,如果我在“MyObject”上重命名属性“myPropertyName”,代码就会中断

也就是说,在不显式键入属性名称的情况下引用属性名称的最简单方法是什么(因为这样可以获得编译器警告)?我看起来像:

for(PropertyDescriptor property : myObjectProperties){
    if(property.getName().equals(MyObject.myPropertyName.getPropertyName())){
         // logic goes here
    }
}

或者这在Java中是可能的?

不可能从一个对象获得声明的字段名,因为多个字段可以等于同一个对象。这里更好地解释了这一点:

您可以通过添加一些注释来定义目标属性。然后在循环中搜索具有所需注释的字段

首先定义一个在运行时可以访问的注释

@Retention(RetentionPolicy.RUNTIME)
public @interface Target {
}
又好又容易, 现在创建使用它的类

public class PropertySearcher {

    int awesome;
    int cool;
    @Target
    int foo;
    int bar;
    String something;
}
现在让我们搜索它

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
            }
        }
    }
}
输出
Fname=int reflection.PropertySearcher.foo
找到属性


通过这种方式,您可以毫无顾虑地重构代码。

很抱歉,您不能这样做,理论上,您可以在每个类中为每个方法定义常量,但我认为这不是解决方案。如果我们提出改进建议,我想我们需要更多关于您的代码设计的信息。你想用代码实现什么?例如,如果您在编译时拥有该属性,为什么要使用反射来访问它?如果在编译时没有,您希望如何使用编译时引用来检索名称?