Vladimir
Vladimir

Reputation: 13163

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.

I.e.

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?

Upvotes: 1

Views: 214

Answers (1)

If you use 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

As suggested I added something in the loop for preventing the VM removing dead code

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

Upvotes: 1

Related Questions