Home > Net >  Gradle Task Modify code before compile (android)
Gradle Task Modify code before compile (android)

Time:01-02

Problem: Modify code prior to compile (a task like obfuscation)

First Approach:

  1. Run a task (backupTask) to backup 'src/main/java' directory
  2. Modify the original code
  3. Restore the backup to get the original code after build

Example:

task backupCode(type:Copy){
    def src = "src/main/java"
    def dst = "src/main/backup"
    from src
    into dst
    filter {String line ->
        line.replace('Hello',"Bello")
    }
    dependsOn 'deleteModified'
}
task restoreCode(type:Copy){
    def src = "src/main/backup"
    def dst = "src/main/java"
    from src
    into dst
}
task deleteModified(type:Delete){
    delete "src/main/modified"
}
preBuild{
    dependsOn 'generateModifiedCode'
    doLast {
        //restore
        restoreCode()
    }
}

Another use case: Modify the annotated function with try catch block

 @WrapFunction
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.e("TAG","Nello World")
    }

Resulted code before compile (but without modifying original)

@WrapFunction
    override fun onCreate(savedInstanceState: Bundle?) {
       try{
           super.onCreate(savedInstanceState)
           setContentView(R.layout.activity_main)
           Log.e("TAG","Nello World")
       }catch (ex:Exception){
           
       }
    }

Required: Is there any best approach to modify code prior to compile without affecting the the original code? The main idea is to create a custom gradle plugin like proguard obfuscation. Which modify the compile code but the original is kept the same.

Note: I have knowledge of Reflection Custom Gradle Plugin Custom Annotation

CodePudding user response:

After a deep research and strugle, I found the answer by my self:

Gradle Transform API Javassist Custom Annotation Custom Gradle Plugin understanding of bytecode

  • Related