Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically editing/creating classes in Java Android

I am looking for a way to dynamically define classes and instantiate them in Android, at runtime. From my understanding, this is already done in Android, I just need some help figuring it out.

I can a similiar result in Javascript and PHP. I know it can be done in Java using something like ASM, BCEL or CGlib. However, I do not know enough about any of these to understand if they will work on Android. Or, of they will work, what are the implications?

If, hypothetically, all three will work in Android, can someone point me in the correct direction as to where to start understanding which to use, and how to use it?

I haven't done much Java programming, and I have only just recently been working with it in Android, so, I appreciate all of the help/correction I can get. With that said, I would appreciate if your answer is NOT simply: Don't do this. I am looking for how to do this specifically, not how to do it right. At least, not until my app comes crashing down. :)

I believe that this already happens in Android in the following situations: (Not 100% SURE)

Creating an object from JSON. AIDL

like image 909
Jonathan Avatar asked Aug 10 '26 19:08

Jonathan


2 Answers

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.

like image 196
Oak Avatar answered Aug 13 '26 11:08

Oak


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.

like image 36
Gordon Williams Avatar answered Aug 13 '26 10:08

Gordon Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!