Link to home
Start Free TrialLog in
Avatar of inzaghi
inzaghi

asked on

method execution on interfaces using reflection

I have a property defined which is a comma seperated list of classes.
Each one of these classes extend a Class A and implement methods of class B.
What I want to do is for each class in this list is to use the Class.forName(className) and
create a instance of this class using class.newInstance().

I know how to do this.
But how would I invoke the methods on class A and Class B.  Would I need to cast the object returned from class.newInstance() to A then invoke its method and then cast to the interface B and invoke its method

 ie  Object o = class.newInstance();
     A objectA = (A) o;
     objectA.doIt();
     B interfaceB = (B) o;
     interfaceB.method1();
     interfaceB.method2();
Avatar of Mick Barry
Mick Barry
Flag of Australia image

You need to either cast,
or you can use reflection to get the Method instance and exeute it.
No - no need to cast to B
> no need to cast to B

yes you would to access the B methods
>>yes you would to access the B methods

No - you shouldn't need to if A implements B
Avatar of inzaghi
inzaghi

ASKER

Class A does not implement B,
public class C extends A implements B{
}
Now you're confusing me - C wasn't mentioned before ;-) In that case you don't need to cast C to B
Avatar of inzaghi

ASKER

Sorry for the confusion, just for clarity c is a actual class name that is defined in the comma seperated list of class names
Question seemed quite clear to me :)
Avatar of inzaghi

ASKER

To invoke the individual methods on the class A and B is it better to cast first or use reflection to get the methods and invoke?
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of inzaghi

ASKER

I will be creating Objects of the class C using:

Object object = Class.forName(className).newInstance();

Now how can I cast this object to its orginal type ie class C, would this do it

C objectC = (className.class) Class.forName(className).newInstance();
Cast as you would normally:

C c =  (C)Class.forName(className).newInstance();
You have a choice:

a. casting as above
b. using reflection to invoke the methods you want to invoke on the Object reference
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:-)