通过反射获取字段名是否是一个应该避免的昂贵操作?

Does the getting field name via reflection is an expensive operation that should be avoided?

我正在编写一些验证代码。

并且不想声明太多常量,因此考虑如何获取 class 的属性名称的更动态的方式。

class User {
   String firstname;
   String lastname;

   getters/setters ....
}

是否通过

访问
User.class.getDeclaredField("firstname").getName();

是一项昂贵的操作,我宁愿使用常量或其他方式?

如果您使用 User.class.getDeclaredField("firstname").getName(); 将给出与参数相同的输出名字。

long init = System.currentTimeMillis();

for(int i = 0; i < 1000000; ++i)
{
    Field[] fields = User.class.getDeclaredFields();

    for(Field field : fields)
    {
        field.getName();
    }
}

System.out.println(System.currentTimeMillis()-init);

该代码只需要 500 毫秒,所以在我看来,字段之间的搜索并不昂贵

按照建议,我在循环中添加了一些东西以防止 VM 删除死代码

public static void main(String[] args) throws Exception {
long init = System.currentTimeMillis();
int count = 0;
for (int i = 0; i < 1000000; ++i) {
    Field[] fields = User.class.getDeclaredFields();
    for (Field field : fields) {
        if (field.getName().equals("firstname")) {
            count++;
        }
    }
}
System.out.println(count);
System.out.println(System.currentTimeMillis() - init);
}