Here’s the first technique for navigating class hierarchies. Note that getSuperclass() returns null when called with a Class object representing the Object class, since Object has no parent. The getSuperclass() method returns a Class object representing the parent or super class of the invoking Class object. The getName() method returns a string representing the Class object’s package and class name. Both methods are called with Class objects. Our program needs the getSuperclass() and getName() methods from the Java Reflection API. We’ll write this program specifically for the JTextField class, but you should be able to easily adapt it to access class names in the inheritance hierarchy of any Java class. Let’s write a Java Reflection program to navigate through this class hierarchy and print out the class and package names. The other classes in between fill in the complete inheritance hierarchy. The Object class is at the top and JTextField is at the bottom. You can see that this class hierarchy is fairly deep. Here’s the class hierarchy for JTextField from the Java API documentation. We’ll need an example to work with, so let’s use the Java Swing TextField class. You’ll learn two techniques to do this, so you can pick the one that best suits your needs. In this post, I’ll show you how to use Java Reflection to navigate class hierarchies. However, sometimes you need to navigate through a class hierarchy. Most of the time a single class is all you need to look at. Java Reflection makes it easy to find fields, methods, and constructors in your Java classes.
0 Comments
Leave a Reply. |