Reputation: 43
I am retrieving a String
variable from the Database
and storing in a variable.
String name = "Peter" ---- >(retrieved from the database)
I already have a class called Peter
. I need to initialize the class using the retrieved variable name
.
Assume that ,whatever String
is retrieved from the database , I have a class defined for it in my package...
Is there a way to create a Object
for the String
I retrieve from the Database
?
Upvotes: 1
Views: 13987
Reputation: 1556
Using Class.forName()
- java.lang.reflect
If we know the name of the class & if it has a public default constructor we can create an object in this way.
Class myClass = Class.forName("MyClass");
Class[] types = {Double.TYPE, this.getClass()};
Constructor constructor = myClass.getConstructor(types);
Object[] parameters = {new Double(0), this};
Object instanceOfMyClass = constructor.newInstance(parameters);
See Java how to instantiate a class from string
Upvotes: 0