简体   繁体   中英

Gradle Task Modify code before compile (android)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM