1

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?

Michael
  • 1,453
  • 3
  • 20
  • 28
ktbffh
  • 43
  • 1
  • 1
  • 5

2 Answers2

6
Class.forName(name).newInstance()
Ken Clubok
  • 1,238
  • 6
  • 11
0

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

Community
  • 1
  • 1
mehere
  • 1,487
  • 5
  • 28
  • 50