gpt4 book ai didi

java - 如何避免 Java 反射中的魔术字符串

转载 作者:搜寻专家 更新时间:2023-10-31 20:11:39 25 4
gpt4 key购买 nike

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

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找到属性(property)。

这样您就可以毫无顾虑地重构您的代码。

关于java - 如何避免 Java 反射中的魔术字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23757561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com