Chapter 8. Reflection and JavaBeans

Chapter 6 and Chapter 7 showed how to use and extend existing Java code with Jython. This chapter offers a slightly different perspective on the use of Java code. It explains not merely how to use the Java code, but also how Jython’s own use of Java reflection can make working with JavaBeans easier from Jython than from Java. This chapter also shows how Python’s own reflection can help you write better code.

Reflection is the ability of an object to find out about its structure, and to operate on that knowledge. Examples include the ability to list all the instance’s attributes, and the ability to invoke a method from its name string. In Java, reflection is managed by the java.lang.reflect package, which defines objects that encapsulate fields and methods. In Python, reflection is a much more integrated part of the language, with the ability of instances (and other language objects) to provide information about themselves built into the core of the way objects are defined.

Reflection is useful because it allows for more flexible and abstract manipulation of objects. For example, consider a case in which a user may change an object’s attributes at runtime from a web form. The result of that change is a series of key/value pairs of the new attributes. Without reflection, you would probably need a large case statement or the equivalent to separately change the appropriate attribute based on the key. With reflection, you can send the object the key ...

Get Jython Essentials now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.