Problem solve Get help with specific problems with your technologies, process and projects.

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()
         Class cls = Class.forName("com.mytests.Example");
         Example example =
      catch (ClassNotFoundException e)
      catch (InstantiationException e)
      catch (IllegalAccessException 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 last published in April 2003

Dig Deeper on Microservices pattern, platforms and frameworks



Find more PRO+ content and other member only offers, here.

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.

Start the conversation

Send me notifications when other members comment.

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

Please create a username to comment.