I recently replaced reflection with bytecode generation in one of my projects. After an evening with the ASM library I had a much faster solution than reflection. It occurred to me that the code was easily reusable, so I created a small project:
http://code.google.com/p/reflectasm/
Usage looks like this:
FieldAccess access = FieldAccess.get(SomeClass.class);
access.set(someObject, "someFieldName", "someValue");
System.out.println(access.get(someObject, "someFieldName"));
Or slightly more efficiently:
int fieldIndex = access.getIndex("someFieldName");
access.set(someObject, fieldIndex, "someValue");
System.out.println(access.get(someObject, fieldIndex));
ReflectASM performance is very close to compiled code, there is just the overhead of calling the get or set method and a switch statement. I’ve only done public field access, I’ll add method access and proper documentation when I find some more free time.
It seems the JIT could generate a class if it detects enough reflection usage. It doesn’t appear to bother. Any good reasons why?
I wouldn’t be surprised if a project like this already exists. If it does, please let me know!