Search code examples
javaandroidcompilationdex

Should I avoid creating classes and compiling them at runtime in Android?


Let' say I have an app that is more or less like an editor and executor of what was created with the editor function. I thought about two ways: I can either develop an algorithm and a structure to perform my job or I can literally write and compile at runtime .java file.

To get a better idea of what I am saying I will create a simplified example. First case scenario, I will create multiple instances of SpecialMove for each creation by the user:

public class SpecialMove{
private String name;
private Type type;
private int damage;
...
}

In the second case scenario, classes that extend SpecialMove would be written and compiled at runtime:

    public class SpecialMove{
        protected Type type;
        protected int damage;
        ...
        }

//this class will be written into a separate file and compiled at runtime
    public class FireBall extends SpecialMove{
        protected Type type;
        protected int damage;
        ...
        }

In the past I've chosen to use the second case scenario but it was an application for desktop. Since I am not much skilled in Android, I would like to ask you if generating Dalvik byte code might be trickier and/or less efficient and in general any pros and cons.


Solution

  • Runtime code generation is banned by the Play Store. You can download scripts in a sandbox like Javascript, but you can't download or compile native code at runtime. If caught doing it your app will be removed. This is a security policy by Google to reduce the risk of malware and trojan horses.

    In fact in general compiling code at runtime, on any platform, is almost certainly a wrong choice. Sounds like a debugging nightmare. You might sometimes download extentions with a plugin system, but you wouldn't be compiling it live.