Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing Groovy scripts embed in Java on runtime for Android

As of version 2.4, Groovy supports Android. I want to run a Groovy script embed in Java in my Android application.

This website explains that this is possible: http://melix.github.io/blog/2014/06/grooid2.html

One of the difficulties of adapting the Groovy language is that, as we said, Groovy is a highly dynamic language. One of its capabilities is executing scripts at runtime. So what if we wanted to type a Groovy script on the device, and execute it directly on it? Is it possible? In fact, yes, it is possible, given that you follow this process:

You can have an application, written in Groovy or not, but in the end, once the application is running, you have Groovy source code that you want to execute. Then it needs to compile the classes, call dex directly on the device, package the result into a jar file on the local filesystem, then load it using a special classloader. So why this is possible, the process is very complex, not straightforward, but more importantly, it is dramatically slow.

I am excited that this is indeed possible, regardless of the speed. There is an example project here: https://github.com/melix/grooidshell-example.

Unfortunately I don't really understand the process. I have the project, which is fairly small, but I am not sure where to be looking at exactly.

Can you point me in the right direction to execute Groovy scripts embed in Java on runtime for Android?

like image 812
Voldemort Avatar asked Dec 08 '14 03:12

Voldemort


People also ask

Is Groovy compatible with Java?

Apache Groovy is a Java-syntax-compatible object-oriented programming language for the Java platform. It is both a static and dynamic language with features similar to those of Python, Ruby, and Smalltalk.

How do I run a Groovy script in STS?

You can now easily run Spring Groovy CLI apps from within STS. Right click a app. groovy file and select Run As >> Spring Groovy CLI. The app will be started and its output appears in a Eclipse Console.


1 Answers

Look more closely at https://github.com/melix/grooidshell-example/blob/master/GroovyDroid/src/main/java/me/champeau/groovydroid/GrooidShell.java

That's create a DexFile (line 71) instance, add a bytecode post processor to the compilation (line 73) to take the generated bytes of the classes and translate it to dex format (line 76) and finally store that in the dexfile instance (line 77). Then get the dalvik bytecode (line 91), use a DexClasLoader (line 136) to load the dalvik/dex classes (line 138).

like image 56
blackdrag Avatar answered Oct 17 '22 17:10

blackdrag