10

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?

1 Answer 1

5
+50

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, I am currently trying to implement your steps. I have a problem with line 136: I don't know what value to use for the classLoader argument. In the example, he receives a ClassLoader object when he initializes his program, but I don't do such thing. What do I do for this argument?
The classloader comes from the activity in that example: github.com/melix/grooidshell-example/blob/master/GroovyDroid/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.