Java版宏定义? 利用Gradle实现编译前-代码动态修改


apply plugin: 'com.android.application'


android {
    ArrayList src_lines
    File versionPropsFile
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.dz.gradleautochangecode"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

          versionPropsFile = file('./src/main/java/com/dz/gradleautochangecode/MainActivity.java')
        if (versionPropsFile.canRead()) {
            def stream = new BufferedReader(new InputStreamReader(new FileInputStream(versionPropsFile), "UTF-8"))
            def lines = stream.readLines()
            src_lines = new ArrayList<String>()
            src_lines.addAll(lines)
            stream.close()
            for (int i = 0; i < lines.size(); i++) {
                def line = lines.get(i)
                if (line.contains("1234")) {
                    lines.set(i, "int i = 4567;")
                }
                if (line.contains("我是未修改过的文字或代码")) {
                    lines.set(i, " return \"我已被Gradle动态修改了...而且int值改成了\"+i;")
                }
            }
            def writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(versionPropsFile), "UTF-8"))
            for (def line : lines) {
                writer.writeLine(line)
            }
            writer.flush()
            writer.close()


            new Thread(new Runnable() {
                @Override
                void run() {
                    Thread.sleep(1000)
                    def writer2 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(versionPropsFile), "UTF-8"))
                    for (def line : src_lines) {
                        writer2.writeLine(line)
                    }
                    writer2.flush()
                    writer2.close()
                }
            }).start()
        }

    }

}


要被动态修改代码的类

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((TextView) findViewById(R.id.tv)).setText(sayHello());
    }

    public String sayHello() {
        int i = 1234;
        return "我是未修改过的文字或代码,而且int值为" + i;
    }
}

运行后

Java版宏定义? 利用Gradle实现编译前-代码动态修改_第1张图片

以上只是概念演示, 说明是可以通过曲线救国的方式去实现宏定义的, 这是我以前研究的后来发现可以通过插件实现…所以后面有空再写吧…

你可能感兴趣的:(Android进阶)