Saturday 10 July 2021

Java/Android equivalent of Objective-C/iOS load() method

For iOS (in Objective-C), every class has a load() method that is called when the class is loaded. iOS seems to load ALL of the classes (or at least all of the ones that have the load() method defined) when the app starts.

I've taken advantage of this in several iOS programs to register handler classes with a centralized message handler, for instance, that takes a message type and uses the handler class to create an instance object specific to each message.

Using load() for this allows the code to do auto-registration without having to list all of the classes somewhere and invoking them by hand - it's less error prone in some sense.

Here's some example code:

Specialized payload object (Update payload class):

@implementation
+(void)load
{
    [Payload registerMessageName:@"Update"
                  forMessageKind:kPayloadUpdate
              withPayloadHandler:[Update class]];
}

Payload message handler

static NSMutableDictionary *s_payloadFactoryDict = nil;
static NSMutableDictionary *s_kindToNameMap = nil;
static NSMutableDictionary *s_nameToKindMap = nil;


@implementation

+(void)registerMessageName:(NSString *)messageName
            forMessageKind:(PayloadKind)kind
        withPayloadHandler:(Class)handlerClass
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_payloadFactoryDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:nil];
        s_kindToNameMap = [[NSMutableDictionary alloc] initWithObjectsAndKeys:nil];
        s_nameToKindMap = [[NSMutableDictionary alloc] initWithObjectsAndKeys:nil];
    });

    NSNumber *kindNum = [NSNumber numberWithInt:kind];

    [s_nameToKindMap setObject:kindNum 
                        forKey:messageName];

    [s_kindToNameMap setObject:messageName
                        forKey:kindNum];

    [s_payloadFactoryDict setObject:handlerClass
                             forKey:kindNum];
} 

I now want to do something similar in Android / Java. Is there a similar approach that is the preferred model?

EDIT/FOLLOW-ON: Is there a good way of using reflection to do this?



from Java/Android equivalent of Objective-C/iOS load() method

No comments:

Post a Comment