Title: create instance
Tags: java;oop
Question: i have a string which contains the class name.
i want to create an instance for that class..
class  Test
in main function
String str="Test";
i have to create instance of the Test class using str variable only...
Comment: Using C++, Java or what?


Here is another answer: You cannot do it natively in C++. Will need to simulate reflection by using some structures (a lookup table maybe) that will associate strings to types, which will create objects for you.

Here is another answer: In Java you have support for reflections by default. In native C++ you don't have reflections. If you need reflections in C++, try using frameworks like Qt.

Here is another answer: Class.forName(str).newInstance();
The above code returns an object of the class. Make sure 'str' has fully qualified class name.

Here is another answer: The generic OOP technique you are trying to describe is called the Abstract Factory pattern, whereby you read data and then decide at runtime what type of class to create.
Normally the class will derive from a known base or else it will have to be some kind of variant type.
For a class that derives from a known base you would then go on to call its virtual/abstract methods (polymorphism). With a variant type you would probably "visit" it.

Here is another answer: Object obj = Class.forName(str).newInstance();

Here is another answer: Test t = (Test) Class.forName(className).newInstance()

Here is another answer: With Java you need to use the Reflection API:
String className = "Test";
Test newInst = (Test)Class.forName(className).newInstance();
C++ has no native Reflection equivalent to Java, so you need to implement it yourself:
void* newInstance(st75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0string className) {
if (className == "Test") {
return new Test();
return 0;

Here is another answer: You have to use a technique called reflection. Here is the Wikipedia article on Reflection (computer programming).
For Java: Have a look at the Class class, specifically the Class.newInstance method.
Here is a simple "Hello World" program to demonstrate:
public class Test {
public static void main(String[] args) throws Exception {
String className = "Test";
Class c = Class.forName(className);
Object o = c.newInstance();
((Test) o).method();
public void method() {
System.out.println("Hello World");

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 8, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 2.5', 'CreationDate': '2011:00:01/27/11', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><oop>', 'Title': 'create instance', 'ViewCount': 452, 'id': 4816860, 'user_AboutMe': '', 'user_AccountId': 290587.0, 'user_DisplayName': 'svKris', 'user_Reputation': 733.0, 'user_Views': 61.0, 'user_id': 592221.0}}