Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

type casting to a class 1

Status
Not open for further replies.

lovekang

Programmer
Feb 16, 2006
86
KR
Class c = Class.forName("javax.crypto.Cipher");
I want to cass my_object to the same type of c.
Is it possible?
if so how?
 
Not sure what you want to do, but if you want to create an object on the fly (ie at runtime), you would do :

Object o = Class.forName("com.acme.MyClass").newInstance();

This relys on the fact that your class has a default constructor.

If it does not have a default contstrucor, you need to use reflection to pass the desired parameters. Eg, to list all the Constructors :

Code:
Class c = Class.forName("com.acme.MyClass");
Constructor[] ctors = c.getConstructors();
for (int i = 0l i < ctors.length; i++) {
  // look for you desired constuctor 
  // and then call the relevant newInstance() method on the 
  // ctor object
}

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top