简体   繁体   English

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

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

I'm writing some validation code. 我正在写一些验证码。

And don't want to declare much constants, so thinking about more dynamic way of how to get a name of properties of a class. 并且不想声明太多的常量,因此考虑了一种更动态的方式来获取类属性的名称。

Ie

class User {
   String firstname;
   String lastname;

   getters/setters ....
}

Is the access via the 是通过

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

is an expensive operation and I rather go with constants or some other way? 是一个昂贵的操作,而我更喜欢使用常量或其他方式?

If you use User.class.getDeclaredField("firstname").getName(); 如果您使用User.class.getDeclaredField("firstname").getName(); that will give as output firstname that is the same that the parameter. 作为输出的名字将与参数相同。

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);

That code takes only 500 ms, so in my opinion search between the fields isn't expensive 该代码仅需500毫秒,因此我认为在字段之间进行搜索并不昂贵

As suggested I added something in the loop for preventing the VM removing dead code 如建议的那样,我在循环中添加了一些内容以防止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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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