Instantiate a class by name stores in String

For beginners like me that are not very familiar with object oriented concepts, it might be impossible to imagine that Java has a capability to instantiate a class by its name stored in a string variable. However, this is totally possible in Java or even in other programming languages with utilizing reflector/reflection concept.

Take a look at below example,

public class A
private int x;
public void setX(int x)
this.x =x;
public int getX()
return this.x;

Now the objective is to create an instance of class ‘A’ which its name stored in variable, this code does that.

public void main(String[] args)
String className =”A”;
Class myClass = Class.forName(className);
//Now need to make an object
Object obj = myClass.newInstance(); // This is a general Object type, must convert to call method.
A aClass = (A) obj;
//Shorter way
A aClass = (A) Class.forName(className).newInstance();

Now it might be a question what the reflector is used for, the answer is so simple, one practical example is making database connection.

You can refer to the following links for DB connection.

Official Oracle website,

Tutorialspoint website,

And finally to know more about reflection refer to this link.


Send your idea and information to

Leave a Reply

Your email address will not be published. Required fields are marked *