I have spend the last 1 or 2 hours diving into Java reflection.
I think i’m starting to have a proper understanding.
I could not however find a few answers I was looking for.
What I came to understand is that reflection suffers a big(biggest?) performance hit from class lookups.
I have 2 questions.
How can you call a method from within the current context(is it even possible?)?
And will the performance hit from class lookups be canceled out when calling within the current context?
for example:
class User {
private String name;
public getName(){ return name; }
public setName(String name){ this.name = name; }
public void doSomething() {
//some random stuff
//I would like this method to invoke randomMethod();
//Since it is within the same context(this)
//Will this reduce the performance cost?
//Please assume from my goals that I will ALWAYS know the name of the method i want to call.
//So I wont need to loop through all available methods.
}
public void randomMethod() {
}
}
Im trying to achieve some kind of dispatcher.
For example for web development in Java.
Im not interested in frameworks etc.
So if a user enters an url http://www.hiurl.com/home/index
Where home is the controller and index the action(the method name to be called by reflection).
If you have good arguments why to absolutely avoid this apart from the many chances of failing, please let me know aswell.
I hope my question is clear.
Thanks for taking the time to read and I look forward to read your replies.
No, unfortunately one cannot optimize subsequent method calls via reflection even if all of them are executed on the same instance. The reason for this basically is the signature of reflection methods for invocation:
The only thing one can do to optimize calls using reflection is to store references to
Method,Field,Constructoretc. in order to avoid costly lookups each invocation e.g:Besides that, I would recommend using Reflection only if it’s highly justified since it hampers performance, is less typesafe and has some other drawbacks. If one can go without Reflection, one should not use it.