Due to Java's class loader system loading a class to make it accessible to the test scripts is not always trivial.
Here is a helper function (loadClass()
) that tries to cover all possible cases.
def main():
startApplication("myaut")
### LOADING THE CLASS:
### Approach #1
# Trying to load without GUI object class loader:
loadClass("com.mine.TheClass")
### Approach #2
# Trying to load without a GUI object class loader,
# but silently (no failure log entries):
loadClass("com.mine.TheClass", verbose=False)
### Approach #3
# Trying to load via GUI object class loader; for GUI
# classes which are not part of standard Java (meaning
# anything that sub-classes AWT or Swing classes, and
# classes that are not part of standard Java, like all
# of SWT):
gui_object = waitForObject("non_standard_java_gui_object")
loadClass("com.mine.TheClass", gui_object)
### ACCESSING/USING THE CLASS:
### #1: Static methods
# Invoking a static method of the class:
something = com_mine.TheClass.getSomething()
### #2: Instance methods
# Invoking a method of the instance (instantiate
# the class first):
theClassInstance = com_mine.TheClass()
somethingElse = theClassInstance.getSomethingElse()
def loadClass(class_name, gui_object=None, verbose=True):
# Try to load via GUI object's class loader:
if gui_object is not None:
cl = gui_object.getClass().getClassLoader()
if not isNull(cl):
try:
return cl.loadClass(class_name);
except:
if verbose:
test.warning("Loading class via GUI object class loader unsuccessful: %s" % class_name)
else:
if verbose:
test.warning("GUI object class loader is null (is the class of the GUI object part of standard Java perhaps?): %s" % class_name)
# Try to load via current context class loader:
try:
# Class.forName uses the current context classloader and if
# that is the boot classloader, apparently only classes from
# rt.jar can be loaded
return gui_object.getClass().forName(class_name)
except:
if verbose:
test.warning("Loading class via current context class loader unsuccessful: %s" % class_name)
# Try to load via system class laoder
cl = java_lang_ClassLoader.getSystemClassLoader()
try:
return cl.loadClass(class_name)
except:
if verbose:
test.warning("Loading class via system class loader unsuccessful: %s" % class_name)
return None