-3

Possible Duplicate:
Create new class from a Variable in Java

i had a scenario like this,

 String className;

 if(someCondition){

 className="A";

   }
 else{
   className='B'
  }

Now i want to do this dynamically

 className obj=(className) dbObj;//i am typcasting the db casting to particular class

Note:Here A and B classes having same setters and getters but belongs to two different tables in db

Community
  • 1
  • 1
Surya Prakash Tumma
  • 2,064
  • 3
  • 23
  • 42

2 Answers2

2

From create-new-class-from-a-variable-in-java

This is what you want to do:

String className = "A"; //or "B"
Object xyz = Class.forName(className).newInstance();

Take a look for Class.forName()

Community
  • 1
  • 1
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100
0

You should modify your design a littel bit.

Both the classes A and B should implement same inteface.

interface IAB {
}

class A implements IAB {
}

class B implements IAB {
}

Now, change your code as following:

IAB className;

if(someCondition) {
    className = (A) dbObj;
}
else {
    className = (B) dbObj;
}

OR

classname = (someCondition ? A : B) dbObj;
Azodious
  • 13,563
  • 1
  • 33
  • 68