Invoke methods of an object using reflection



This java code example shows how to invoke methods on an object at runtime without knowing the names of them in advance.
This is possible using the reflection API. What we do is to get an instance of the class object of the particular class we want to call methods on and by using that instance we can get the array of Method objects by calling getDeclaredMethods().
We don’t actually call the methods of the class instance, instead we have to create an object that we call the methods on by sending it as an argument to the invoke() method.
In this example we use an inner class named ‘Computer’ but of course it could be any object, not necessarily an instance of an inner class. The names of the methods invoked are printed out along with the values that they return.

The output of the code above is:







Search for more Java info on this site here:
Custom Search


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">