jeudi 16 septembre 2021

What does "loading a class" mean with the Android Runtime (ART) when using reflection?

I try to understand the process of ART when using reflection. As it can be seen in the simple example below, the DexClassLoader is used to load a class from the DEX-file. The question now is what is ART doing internally when loading a class?

From other sources, I found out that the previously used dalvikVM loads the bytecode of the class into memory and initializes static content during loading. The bytecode can then be interpreted by the dalvikVM (e.g. creating an instance of that class).

The Android documentation states that ART uses Ahead-of-time (AOT) compilation, which converts the bytecode in a DEX-file into some optimized code that is then executed on the device.

So, if I load a class via reflection is it compiled again and then executed? Or does it work the same way it did with the dalvikVM by loading and interpreting the bytecode?

Example:

ClassLoader cl = Thread.currentThread().getContextClassLoader();
DexClassLoader dexClassLoader = new DexClassLoader("path/to/dex", null, ".", cl);

Class<?> loadedClass = dexClassLoader.loadClass("com.package.MyClass");
            
Object instance = loadedClass.newInstance();

Method method = loadedClass.getDeclaredMethod("myMethodName", String.class);

Object result = method.invoke(instance, "my method input");

I would appreciate any additional information on this topic. Thanks!





Aucun commentaire:

Enregistrer un commentaire