I was looking as the question : Instantiate a class from its string name which describes how to instantiate a class when having its name. Is there a way to do it in Java? I will have the package name and class name and I need to be able to create an object having that particular name.
Share
Two ways:
Method 1 – only for classes having a no-arg constructor
If your class has a no-arg constructor, you can get a
Classobject usingClass.forName()and use thenewInstance()method to create an instance (though beware that this method is often considered evil because it can defeat Java’s checked exceptions).For example:
Method 2
An alternative safer approach which also works if the class doesn’t have any no-arg constructors is to query your class object to get its
Constructorobject and call anewInstance()method on this object:Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like: