用于安卓的Java8标准库 – retropiler

Retropiler

“Java8 support” in Android is sometimes misunderstood because it includes a few independent issues.

Java8 Language Feature is usually syntactic one, for example lambda expressions or default methods; in Android, this is solved by tools likeretrolambdaordesugar.

Java8 API, or Standard Library, is runtime library on the platform. The support of Standard Library in Android is more difficult than Language Feature, because dex, Dalvik executable file format, does not allow bundle Standard Library in APK. In fact, it was considered impossible — before this project shows its possibility.

Retropiler deals with the latter: it makes dex to bundle Java8 standard library by replacing its references to the original ones.

For example, the following code works on devices with Android API level 15 after processing by retropiler:

import java.util.Optional;

Optional<String> optStr = Optional.of("foo");

assertThat(optStr.get(), is("foo")); // it works!

Here is the magic.

The basic idea is that replacing Java8-specifc classes / methods to the bundled version of them with bytecode weaving.

That is, the above code is transformed into:

import io.github.retropiler.runtime.java.util._Optional;

_Optional<String> optStr = _Optional.of("foo");

assertThat(optStr.get(), is("foo")); // it works!

It can work even on Android API 15.

Installation

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'io.github.retropiler:retropiler-gradle-plugin:0.0.5'
    }
}

apply plugin: 'io.github.retropiler'

Supported Classes

Iterable#forEach()

Arrays.asList("foo", "bar").forEach(item -> {
    Log.d("XXX", item);
});

java.util.Optional

Optional<String> optStr = Optional.of("baz");
optStr.ifPresent(str -> {
    Log.d("XXX", str);
});

Part ofjava.util.functionpackage

Not all the functions are tested yet.

Customizing Runtime Class Mapping

You can customize mapping of stndard class to alternative runtime class:

apply plugin: 'io.github.retropiler'

retropiler {
    // the default runtime package
    runtimePackage "io.github.retropiler.runtime"

    // the default mapping function
    mapClassName { ext, ctClass ->
        // e.g. map java.util.Optional to io.github.retropiler.runtime.java.util._Optional
        "${ext.runtimePackage}.${ctClass.packageName}._${ctClass.simpleName}"
    }
}

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:用于安卓的Java8标准库 – retropiler