[SalesForce] Running class Id in apex

Like we have System class method currentPageReference() to get the reference of current Visualforce Page. Do we have something similar to get the details of running Apex Class?

My requirement is to check status of previous instance of my Batch class when it ran last time. Depending on that I need to set certain attributes of current instance.

Currently I am storing Batch Class Id in custom setting and referring that while querying AsyncApexJob for status. Just wondering if there any other way.

Best Answer

Notice that the Database.Batchable interface methods all accept a Database.BatchableContext instance (documentation) as a parameter. This object has a method called getJobId().

public void finish(Database.BatchableContext context)
{
    system.debug([SELECT ApexClassId FROM AsyncApexJob WHERE Id = :context.getJobId()]);
}

Otherwise, you can query for it. You can write a system wide cache or query for the specific record.

static Map<String, ApexClass> cache
{
    get
    { // Lazy Load Pattern
        if (cache == null)
        {
            cache = new Map<String, ApexClass>();
            for (ApexClass classInstance : [SELECT Name FROM ApexClass])
                classes.put(classInstance.Name, classInstance);
        }
        return cache;
    }
    private set;
}
static Id currentClassId
{
    get
    { // Lazy Load Pattern
        if (currentClassId == null)
        {
            currentClassId = [
                SELECT Id FROM ApexClass
                WHERE Name = '<current_class>'
                LIMIT 1
            ].Id;
        }
        return currentClassId;
    }
    private set;
}
Related Topic