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

MyClass:

The output from the example will be:







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="">