Roman
Roman

Reputation: 131228

Can an object know from which object its method is called?

In Moritz Haarmann's Blog I found an example of usage of Bonjour by Java. Here is the code taken from there:

public class ServiceAnnouncer implements IServiceAnnouncer, RegisterListener {
    private DNSSDRegistration serviceRecord;
    private boolean registered;

    public boolean isRegistered(){
        return registered;
    }

    public void registerService()  {
        try {
            serviceRecord = DNSSD.register(0,0,null,"_killerapp._tcp", null,null,1234,null,this);
        } catch (DNSSDException e) {
            // error handling here
        }
    }

    public void unregisterService(){
        serviceRecord.stop();
                registered = false;
    }

    public void serviceRegistered(DNSSDRegistration registration, int flags,String serviceName, String regType, String domain){
        registered = true;
    }

    public void operationFailed(DNSSDService registration, int error){
        // do error handling here if you want to.
    }
}

I have a question about the "serviceRegistered" method. As far as I understand it is called during (or after) registration of the service (and it sets variable "registered" to be equal to "true"). But what is not clear to me is how exactly it is called. Because the service is registered by the method "registerService". This method, in its turn, calls "DNSSD.register". And, as far as I understand, the "DNSSD.register" will call the "serviceRegister" method of the "ServiceAnnouncer" class. But how "DNSSD.register" knows that it needs to call a method of the "ServiceAnnouncer" class? Can "DNSSD.register" know that it is called from a particular class (in this case "ServiceAnnouncer" class)?

Upvotes: 0

Views: 272

Answers (2)

Bozho
Bozho

Reputation: 597254

It seems that this class is a listener - namely RegisterListener. It has been registered as a listener in DNSSD by passing itself to the register(..) method.

For more information read about the Observer pattern.

Upvotes: 1

BalusC
BalusC

Reputation: 1109272

The ServiceAnnouncer has passed itself as last argument of the DNSSD.register() method, which in turn is apparently expecting any instance of RegisterListener. This way the DNSSD can have a direct handle to the ServiceAnnouncer instance.

Upvotes: 4

Related Questions