Instantiate a class by name stores in String in Java

Default featured post

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 class Test {
    public void main(String[] args) {
        String className = "A";
        Class myClass = Class.forName(className);
        //Now need to make an object
        // This is a general Object type, must convert to call method.
        Object obj = myClass.newInstance(); 
        A aClass = (A) obj;
        //Shorter way
        A aClass = (A) Class.forName(className).newInstance();

Now it might be a question what the reflection 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.