Regardless if it is a good or bad OO practice to provide accessors in a class, I'd like to know if executing access to a specific attribute of an object via reflection decrease performance (memory consumption or cpu time).
Have you implemented this and performed a benchmark? Do you know about anyone who has performed such benchmark?
Edit:
Due to some comments which indicates that it's obvious that performance decrease I've modified the title of the question to indicates that I'd like to know how bad is the impact of implementing accessors with reflection.
Edit:
Thank you for your kind comments and answers. Based on the answer from @Peter Lawrey and the kind comment from @EJP, this is what I meant and wanted to know if any of you have implemented prior to my question:
package co.com.prueba.reflection;
import java.lang.reflect.Field;
public class A {
private String s;
public void setS(String s){
this.s=s;
}
public String getS(){
return this.s;
}
public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
System.out.println("Invoking .setAccesible(true) ...");
A secondA = new A();
for(int i=0; i<10; i++){
long start = System.nanoTime();
Field f = secondA.getClass().getDeclaredField("s");
f.setAccessible(true);
f.get(secondA);
long end = System.nanoTime();
System.out.println((end - start));
}
System.out.println("Without invoking .setAccesible(true) ...");
A firstA = new A();
for(int i=0; i<10; i++){
long start = System.nanoTime();
Field f = firstA.getClass().getDeclaredField("s");
f.get(firstA);
long end = System.nanoTime();
System.out.println((end - start));
}
System.out.println("Invoking the getter ...");
A thirdA = new A();
for(int i=0; i<10; i++){
long start = System.nanoTime();
thirdA.getS();
long end = System.nanoTime();
System.out.println((end - start));
}
}
}
Here are the results:
Thank you all.