Q

Declaring an object at runtime

Is there any possibility of declaring an object at runtime? Please see the following example:


class Example 
{
   public static void main(String[] args) 
   {
      String str = "Example";
      //Declaring Object at runtime 
      String e = new str();

      System.out.println("Hello World!");
   }
}
My goal is to declare an Example class object at runtime. Is it possible?

One of the primary benefits of Java is its flexibility and dynamic behavior at runtime. Java is a very descriptive language and affords a wide variety of discovery and invocation features at compile-time and runtime.

Your particular problem is solved very nicely with Java's core classes and packages; in particular, java.lang.Class. Let's assume for a moment that your example class is declared as follows:

   package com.mytests.Example;

   public class Example
   {
      public Example()
      {
         System.out.println("Hello from example!");
      }
   }
We can easily construct an instance of Example at runtime with the following code:
   public Test()
   {
      try
      {
         Class cls = Class.forName("com.mytests.Example");
         Example example =
            (Example)cls.newInstance();
      }
      catch (ClassNotFoundException e)
      {
         System.err.println(e);
      }
      catch (InstantiationException e)
      {
         System.err.println(e);
      }
      catch (IllegalAccessException e)
      {
         System.err.println(e);
      }
   }
The preceding example demonstrates how we can construct and instance of the com.mytests.Example class "template" at runtime. The "template" is then used to create an actual instance of com.mytests.Example.

Note that the "forName" method requires the fully-qualified (package plus class) name do be used and the "newInstance" method requires a "no-arg" constructor to be present in order perform the instantiation.

Further information about the details of Java's class structure and runtime capabilities can be found in the "Learning the Java Language" tutorial and in the "The Reflection API" tutorial.


This was first published in April 2003

Dig deeper on Java Web Services

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchSoftwareQuality

SearchCloudApplications

SearchAWS

TheServerSide

SearchWinDevelopment

Close