Instantiate unknown class at runtime and call the object’s methods

This java code example shows how to create an object at runtime for which the name of the class is not know at compile time.
We use the forName() method to load the class and then use the newInstance() method to create the object.
Then we use reflection to get the methods of the class and invoke them. The class we are instantiating is called MyClass (see further below) and we assume that
the methods we are interested in starts with the string ‘say’ (we don’t want to call all the methods inherited from java.lang.Object).

Continue reading

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.

Continue reading

List methods of a class using Reflection

In this example we use the Reflection api to obtain the methods of a particular class called Person, which is an inner class.
First we need to get the Class object and we do so by calling ‘Person.class’. Once we have the Class object we can use it to call the getDeclaredMethods() method which will return an array of type Method.
To find out the names of the methods that the Person class contains we simply loop through the array and call getName() for each Method object.

Continue reading