Ask the Expert

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?

    Requires Free Membership to View

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

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: