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,

https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html

Tutorialspoint website,

http://www.tutorialspoint.com/jdbc/jdbc-db-connections.htm

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

Stackoverflow,

http://stackoverflow.com/questions/9886266/is-there-a-way-to-instantiate-a-class-by-name-in-java

Send your idea and information to kasra@madadipouya.com

Leave a Reply