Reputation: 15432
I think that my question is not very clear :) Here is my problem (in more details):
I have got several objects (lets say objA, objB, objC, etc...) which are instances from different classes (lets say ClassA, ClassB, ClassC... respectively).
These objects A, B, C,..., call the same object (let's call it jsonConnector, instance of JsonConnector class) and I want then this jsonConnector to call the updateUI() method of the object by which it has been created.
Code in my ClassX (ClassA, ClassB, etc...) class:
JsonConnector jsonConnector = new JsonConnector(this);
Constructor of my JsonConnector class:
private Object callingObject;
public JsonConnector(Object aCallingObject) {
callingObject = aCallingObject
}
Somewhere in my JsonConnector class, I want to do:
aCallingObject.updateUI();
but I have got a compiling error "The method updateUI() is undefined for the type Object"
I could do :
String callingClassName = callingObject.getClass().getSimpleName();
if(callingClassName == "ClassA")
{
((ClassA)aCallingObject).updateUI();
}
else if(callingClassName == "ClassB")
{
((ClassB)aCallingObject).updateUI();
}
else if...
But it I don't want to write 100 'else if' statements !
Anybody knows how I can do ?
Thanks !!!
Upvotes: 2
Views: 2511
Reputation: 10995
I think you could program to an interface.
public interface GuiUpdate
{
void UpdateUI() ;
}
//do the same for classes that updates a gui.
public class ClassA implements GuiUpdate
Do you have control over JsonConnector? If so, inject the object references:
public JsonConnector(GuiUpdate updater)
To add, this means you can simply do the following in a subsequent method, polymorphism and abstraction at its finest:
updater.UpdateUI() ;
Upvotes: 4
Reputation: 9609
You can use reflection. But don't use it if you have other solutions.
callingObject.getClass().getMethod("updateUI").invoke(callingObject);
Upvotes: 1
Reputation: 1363
You can create an interface
, which contains the updateUI
method.
Make sure that all of those objects implement
that interface
.
Then pass them to the JsonConnector
using MyInterface
instead of Object
:
private CalleeInterface callingObject;
public JsonConnector(CalleeInterface aCallingObject) {
callingObject = aCallingObject
}
Upvotes: 1