Dynamically Editing/creating Classes In Java Android
Solution 1:
Don't do this :)
I actually doubt there are JSON libraries that behave this way; the two accepted ways I know (I am not an expert on this, though) are either to create some sort of data structure holding name-value pairs - i.e. add stuff to a data structure but not create a new class - or prepare a template of a class which will be populated from a JSON object.
Java, being statically-typed, is not really suitable for creating whole new classes at run-time, and there is no reflection support for that - though there is support for accessing objects of unknown types (e.g. querying for all their fields / methods).
What you can do is to manually write a java class to a file - either in Java code and then compile it somehow, or directly in bytecode - and then load that file at runtime. It's ugly, but it will work. Then it's just the same as any runtime loading of classes - either you rely on the base class / interface of the loaded class, or you have to use reflection to do anything meaningful with it.
Solution 2:
For those who really do want to do this (for instance using Dalvik's JIT to create a fast interpreter for another language), there is this project:
http://code.google.com/p/dexmaker/
Which allows you to programatically create classes, variables and methods.
Solution 3:
Generating Dalvik Bytecode at Runtime on-device Using ASM or BCEL
This example use ASM and BCEL to generete two classes on-device. The classes are created into SD Card memory and then they are loaded into Android operating system dynamically.
The following class is the template of the example:
public class HelloWorld {
public static void hello(){
int a=0xabcd;
int b=0xaaaa;
int c=a-b;
String s=Integer.toHexString(c);
System.out.println(s);
}
}
Firstly I have used BCEL or ASM to create a new ad-hoc class in SD Card. Secondly I have converted the Java Class to a Dex Class with the Dxclient utiliy in SD Card. Finally I have created a jar file and then I have loaded this package into the device from SD Card
DXClient reference
https://github.com/headius/dexclient/blob/master/src/DexClient.java
Post a Comment for "Dynamically Editing/creating Classes In Java Android"