ktbffh
ktbffh

Reputation: 43

how to convert a String to Object in JAVA

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

Answers (2)

mehere
mehere

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

Ken Clubok
Ken Clubok

Reputation: 1238

Class.forName(name).newInstance()

Upvotes: 6

Related Questions