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).


The output from the example will be:

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

Please type any questions here.