dexmaker


Source link: https://github.com/crittercism/dexmaker

Dexmaker

A Java-language API for doing compile time or runtime code generation targeting the Dalvik VM. Unlike cglib or ASM, this library creates Dalvik .dex files instead of Java .class files.

It has a small, close-to-the-metal API. This API mirrors the Dalvik bytecode specification giving you tight control over the bytecode emitted. Code is generated instruction-by-instruction; you bring your own abstract syntax tree if you need one. And since it uses Dalvik's dx tool as a backend, you get efficient register allocation and regular/wide instruction selection for free.

What does it do?

Mockito Mocks

Dexmaker lets you use the Mockito mocking library in your Android projects by generating Dalvik bytecode class proxies. Just add an androidTestCompile dependency on dexmaker-mockito and you can use Mockito in your Android Instrumentation tests.

The version of Mockito that Dexmaker targets can be found in dexmaker-mockito's build.gradle file. The general rule is that the major and minor version of Dexmaker will match the underlying major and minor version of Mockito.

Class Proxies

Dexmaker includes a stock code generator for class proxies. If you just want to do AOP or class mocking, you don't need to mess around with bytecodes.

Runtime Code Generation

This example generates a class and a method. It then loads that class into the current process and invokes its method.

public final class HelloWorldMaker {

  public static void main(String[] args) throws Exception {

DexMaker dexMaker = new DexMaker();

 // Generate a HelloWorld class.

TypeId<?> helloWorld = TypeId.get("LHelloWorld;");

dexMaker.declare(helloWorld, "HelloWorld.generated", Modifier.PUBLIC, TypeId.OBJECT);

generateHelloMethod(dexMaker, helloWorld);

 // Create the dex file and load it.

File outputDir = new File(".");

ClassLoader loader = dexMaker.generateAndLoad(HelloWorldMaker.class.getClassLoader(),

  outputDir, outputDir);

Class<?> helloWorldClass = loader.loadClass("HelloWorld");

 // Execute our newly-generated code in-process.

helloWorldClass.getMethod("hello").invoke(null);

  
}

/** 
  * Generates Dalvik bytecode equivalent to the following method. 
  *
 public static void hello() {
 
  *

  int a = 0xabcd; 
  *

  int b = 0xaaaa; 
  *

  int c = a - b; 
  *

  String s = Integer.toHexString(c);
 
  *

  System.out.println(s);
 
  *

  return; 
  *
 
}
 
  */
  private static void generateHelloMethod(DexMaker dexMaker, TypeId<?> declaringType) {

// Lookup some types we'll need along the way.

TypeId<System> systemType = TypeId.get(System.class);

TypeId<PrintStream> printStreamType = TypeId.get(PrintStream.class);

 // Identify the 'hello()' method on declaringType.

MethodId hello = declaringType.getMethod(TypeId.VOID, "hello");

 // Declare that method on the dexMaker. Use the returned Code instance

// as a builder that we can append instructions to.

Code code = dexMaker.declare(hello, Modifier.STATIC | Modifier.PUBLIC);

 // Declare all the locals we'll need up front. The API requires this.

Local<Integer> a = code.newLocal(TypeId.INT);

Local<Integer> b = code.newLocal(TypeId.INT);

Local<Integer> c = code.newLocal(TypeId.INT);

Local<String> s = code.newLocal(TypeId.STRING);

Local<PrintStream> localSystemOut = code.newLocal(printStreamType);

 // int a = 0xabcd;

code.loadConstant(a, 0xabcd);

 // int b = 0xaaaa;

code.loadConstant(b, 0xaaaa);

 // int c = a - b;

code.op(BinaryOp.SUBTRACT, c, a, b);

 // String s = Integer.toHexString(c);


MethodId<Integer, String> toHexString

  = TypeId.get(Integer.class).getMethod(TypeId.STRING, "toHexString", TypeId.INT);

code.invokeStatic(toHexString, s, c);

 // System.out.println(s);


FieldId<System, PrintStream> systemOutField = systemType.getField(printStreamType, "out");

code.sget(systemOutField, localSystemOut);

MethodId<PrintStream, Void> printlnMethod = printStreamType.getMethod(

  TypeId.VOID, "println", TypeId.STRING);

code.invokeVirtual(printlnMethod, null, localSystemOut, s);

 // return;

code.returnVoid();

  
}
 
}

Download

For Mockito support, download the latest .jar via Maven:

 <dependency>

 <groupId>com.linkedin.dexmaker</groupId>

 <artifactId>dexmaker-mockito</artifactId>

 <version>2.2.0</version>

 <type>pom</type>
  </dependency>

or Gradle:


 androidTestCompile 'com.linkedin.dexmaker:dexmaker-mockito:2.2.0' 

Note: The dependency on Mockito will be transitively included, so there's no need to specify both Mockito AND dexmaker-mockito

You can also download the files manually from Bintray if you prefer.

Resources

A simple bottom sheet view for Android.

A simple video player.

A simple change color of star in rating bar.

An android library that makes it really easy to deal with dynamic permissions. Based on the context, library automatically decides whether to show a dialog (in case app is in foreground) or a notification (in case permission is required by a background service).

An android library to effortlessly connect to available WiFi networks.

A view pager indicator view to deal with a large amount of pages. Nice scale and transition animations are supported.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes