Class Loader Example

This example shows how to find and load a class from a library and call its methods.

A screenshot of the application.

We import the classes that will be needed by the application. The most relevant to this example is the ClassLoader class.

from java.lang import ClassLoader, ClassNotFoundException, String
from java.lang.reflect import Method
from android.view import View
from android.widget import ScrollView, TextView
from serpentine.activities import Activity
from serpentine.widgets import VBox

We define a class based on a custom Activity class provided by the serpentine package. This represents the application, and will be used to present a graphical interface to the user.

The initialisation method simply calls the corresponding method in the base class. This must be done even if no other code is included in the method.

class ClassLoaderActivity(Activity):

    def __init__(self):

We use the onCreate method to set up the user interface which consists of a scrolling text display.

    def onCreate(self, bundle):
        Activity.onCreate(self, bundle)
        self.view = TextView(self)
        scrollView = ScrollView(self)
        layout = VBox(self)

The following method performs the task of loading a class and displaying information about its methods in the text view. We begin by creating an empty string and obtaining the default system class loader so that we can ask for information about a class.

    def loadClass(self):
        s = ""
        loader = ClassLoader.getSystemClassLoader()

In the following try...except structure we load the class and introspect it, obtaining information about its methods, and we add this to the string.

            cl = loader.loadClass("android.os.Vibrator")
            s += str(cl) + "\n"
            for method in cl.getMethods():
                s += "  " + str(method) + "\n"
        except ClassNotFoundException, e:

If the class cannot be loaded we simply show the exception that is raised in the TextView. Otherwise, if all went well, we show the information that we have compiled about the class.

The Class Loader Method Call example takes the use of ClassLoader further in order to call a method of an instance of the Vibrator class.