0

I am trying to add @AuraEnabled annotation to apex class dynamically without any manual intervention.

I have used below soql to fetch the body of the apex class.

ApexClass classNameList = [SELECT body FROM ApexClass where name=:choosenClass limit 1];

How to update the body to add annotation. I tried to convert body to list of String and add annotation using FOR loop but it is not working.

Input:

public class MyMapController {

public static Map<String, String> getMyMap(){
    Map<String, String> myMap=new Map<String, String>();
    myMap.put('key1', 'Apple');
    myMap.put('key1', 'Mango');
    myMap.put('key1', 'Orange');
    myMap.put('key1', 'Banana');

    return myMap;
}

}

Output:

public class MyMapController {
@AuraEnabled
public static Map<String, String> getMyMap(){
    Map<String, String> myMap=new Map<String, String>();
    myMap.put('key1', 'Apple');
    myMap.put('key1', 'Mango');
    myMap.put('key1', 'Orange');
    myMap.put('key1', 'Banana');

    return myMap;
}

}

Please help!!

  • What is the scenario you are trying to achieve? Are you looking to scan apex classes and dynamically add the annotation? Simplest way to do so would be to evaluate and transform. If you still want to kind of automate it, you can read the class say using tooling api and use say a java program to rewrite the new class with annotation. – Jayant Das Apr 5 '18 at 3:39
  • I have VF page in that I have created drop down of apex classes names and there is command button. So when I select the class from drop down I will passed its name to the method present in the apex class. On click of the button that method will execute and internally add AuraEnabled annotation before each methods. @JayantDas – Developer Apr 5 '18 at 4:01
1

While you can use Tooling API to do so, you should also review why you need to add the annotation dynamically. Any aura enabled method ties back to a particular scenario to a lightning component. Remember you still need to address security within those method and be careful while exposing data that you may have within the existing general utility class after it has been converted to an aura enabled method.

The best approach should be to evaluate such classes, confirm if the need be to use methods as aura enabled and convert those with required modifications to incorporate best practices for lightning and aura controllers.

0

You need to use tooling apis for updating classes dynamically. You need to update body field of ApexClassMember in tooling api.

ApexClassMember

Represents the working copy of an Apex class for editing, saving or compiling in a MetadataContainer.

Reference link:

https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_apexclassmember.htm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.