Casting from a class that was passed as a string.
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Wednesday, February 13, 2002 03:23 AM

I have the following code:

			
Object myObject = Class.forName("package.MyClass").newInstance();

and now I need to execute a method that is implemented by "MyClass".
How can I cast "myObject" to a "MyClass" instance when I can't know in advance which Class "MyClass" is?. Is there any other way to do what I am asking?.
Suggestions accepted.

Re: Casting from a class that was passed as a string.

Posted By:   Randy_McLaughlin  
Posted On:   Tuesday, February 19, 2002 08:17 AM

The Class class also implements a getMethod method in addition of the newInstance method. The getMethod method returns a Method object, which includes an invoke method. Through this route you can dynamically invoke a method.


The Class class also implements a getMethods method that can be used to determine all the methods implemented by the class. Using this you could determine whether an object implements a given method and if so, to invoke it.

Re: Casting from a class that was passed as a string.

Posted By:   Bozidar_Dangubic  
Posted On:   Wednesday, February 13, 2002 07:14 AM

what do you mean you do not know which Class MyClass is??? it is package.MyClass Class. you created it using Class.forName("package.MyClass").newInstance(); so myObject is package.MyClass. so if you want to execute a method that is in package.MyClass use ((package.MyClass)myObject).someMethodOfMyClass();
About | Sitemap | Contact