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

Join the conversationComment
Share
Comments
Results
Contribute to the conversation