Uses reflection and JavaBeans introspection to : Reflection « Language Basics « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » Language Basics » ReflectionScreenshots 
Uses reflection and JavaBeans introspection to
Uses reflection and JavaBeans introspection to

/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.com/javaexamples2.
 */

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 * This class is a program that uses reflection and JavaBeans introspection to
 * create a set of named components, set named properties on those components,
 * and display them. It allows the user to view the components using any
 * installed look-and-feel. It is intended as a simple way to experiment with
 * AWT and Swing components, and to view a number of the other examples
 * developed in this chapter. It also demonstrates frames, menus, and the
 * JTabbedPane component.
 */
public class ShowComponent {
  // The main program
  public static void main(String[] args) {
    // Process the command line to get the components to display
    Vector components = getComponentsFromArgs(args);

    // Create a frame (a window) to display them in
    JFrame frame = new JFrame("ShowComponent");

    // Handle window close requests by exiting the VM
    frame.addWindowListener(new WindowAdapter() { // Anonymous inner class
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });

    // Set up a menu system that allows the user to select the
    // look-and-feel of the component from a list of installed PLAFs
    JMenuBar menubar = new JMenuBar()// Create a menubar
    frame.setJMenuBar(menubar)// Tell the frame to display it
    JMenu plafmenu = createPlafMenu(frame)// Create a menu
    menubar.add(plafmenu)// Add the menu to the menubar

    // Create a JTabbedPane to display each of the components
    JTabbedPane pane = new JTabbedPane();

    // Now add each component as a tab of the tabbed pane
    // Use the unqualified component classname as the tab text
    for (int i = 0; i < components.size(); i++) {
      Component c = (Componentcomponents.elementAt(i);
      String classname = c.getClass().getName();
      String tabname = classname
          .substring(classname.lastIndexOf('.'1);
      pane.addTab(tabname, c);
    }

    // Add the tabbed pane to the frame. Note the call to getContentPane()
    // This is required for JFrame, but not for most Swing components
    frame.getContentPane().add(pane);

    // Set the frame size and pop it up
    frame.pack()// Make frame as big as its kids need
    frame.setVisible(true)// Make the frame visible on the screen

    // The main() method exits now but the Java VM keeps running because
    // all AWT programs automatically start an event-handling thread.
  }

  /**
   * This static method queries the system to find out what Pluggable
   * Look-and-Feel (PLAF) implementations are available. Then it creates a
   * JMenu component that lists each of the implementations by name and allows
   * the user to select one of them using JRadioButtonMenuItem components.
   * When the user selects one, the selected menu item traverses the component
   * hierarchy and tells all components to use the new PLAF.
   */
  public static JMenu createPlafMenu(final JFrame frame) {
    // Create the menu
    JMenu plafmenu = new JMenu("Look and Feel");

    // Create an object used for radio button mutual exclusion
    ButtonGroup radiogroup = new ButtonGroup();

    // Look up the available look and feels
    UIManager.LookAndFeelInfo[] plafs = UIManager
        .getInstalledLookAndFeels();

    // Loop through the plafs, and add a menu item for each one
    for (int i = 0; i < plafs.length; i++) {
      String plafName = plafs[i].getName();
      final String plafClassName = plafs[i].getClassName();

      // Create the menu item
      JMenuItem item = plafmenu.add(new JRadioButtonMenuItem(plafName));

      // Tell the menu item what to do when it is selected
      item.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          try {
            // Set the new look and feel
            UIManager.setLookAndFeel(plafClassName);
            // Tell each component to change its look-and-feel
            SwingUtilities.updateComponentTreeUI(frame);
            // Tell the frame to resize itself to the its
            // children's new desired sizes
            frame.pack();
          catch (Exception ex) {
            System.err.println(ex);
          }
        }

      });

      // Only allow one menu item to be selected at once
      radiogroup.add(item);
    }
    return plafmenu;
  }

  /**
   * This method loops through the command line arguments looking for class
   * names of components to create and property settings for those components
   * in the form name=value. This method demonstrates reflection and JavaBeans
   * introspection as they can be applied to dynamically created GUIs
   */
  public static Vector getComponentsFromArgs(String[] args) {
    Vector components = new Vector()// List of components to return
    Component component = null// The current component
    PropertyDescriptor[] properties = null// Properties of the component
    Object[] methodArgs = new Object[1]// We'll use this below

    nextarg: // This is a labeled loop
    for (int i = 0; i < args.length; i++) { // Loop through all arguments
      // If the argument does not contain an equal sign, then it is
      // a component class name. Otherwise it is a property setting
      int equalsPos = args[i].indexOf('=');
      if (equalsPos == -1) { // Its the name of a component
        try {
          // Load the named component class
          Class componentClass = Class.forName(args[i]);
          // Instantiate it to create the component instance
          component = (ComponentcomponentClass.newInstance();
          // Use JavaBeans to introspect the component
          // And get the list of properties it supports
          BeanInfo componentBeanInfo = Introspector
              .getBeanInfo(componentClass);
          properties = componentBeanInfo.getPropertyDescriptors();
        catch (Exception e) {
          // If any step failed, print an error and exit
          System.out.println("Can't load, instantiate, "
              "or introspect: " + args[i]);
          System.exit(1);
        }

        // If we succeeded, store the component in the vector
        components.addElement(component);
      else // The arg is a name=value property specification
        String name = args[i].substring(0, equalsPos)// property name
        String value = args[i].substring(equalsPos + 1)// property
                                 // value

        // If we don't have a component to set this property on, skip!
        if (component == null)
          continue nextarg;

        // Now look through the properties descriptors for this
        // component to find one with the same name.
        for (int p = 0; p < properties.length; p++) {
          if (properties[p].getName().equals(name)) {
            // Okay, we found a property of the right name.
            // Now get its type, and the setter method
            Class type = properties[p].getPropertyType();
            Method setter = properties[p].getWriteMethod();

            // Check if property is read-only!
            if (setter == null) {
              System.err.println("Property " + name
                  " is read-only");
              continue nextarg; // continue with next argument
            }

            // Try to convert the property value to the right type
            // We support a small set of common property types here
            // Store the converted value in an Object[] so it can
            // be easily passed when we invoke the property setter
            try {
              if (type == String.class) { // no conversion needed
                methodArgs[0= value;
              else if (type == int.class) { // String to int
                methodArgs[0= Integer.valueOf(value);
              else if (type == boolean.class) { // to boolean
                methodArgs[0= Boolean.valueOf(value);
              else if (type == Color.class) { // to Color
                methodArgs[0= Color.decode(value);
              else if (type == Font.class) { // String to Font
                methodArgs[0= Font.decode(value);
              else {
                // If we can't convert, ignore the property
                System.err.println("Property " + name
                    " is of unsupported type "
                    + type.getName());
                continue nextarg;
              }
            catch (Exception e) {
              // If conversion failed, continue with the next arg
              System.err.println("Can't convert  '" + value
                  "' to type " + type.getName()
                  " for property " + name);
              continue nextarg;
            }

            // Finally, use reflection to invoke the property
            // setter method of the component we created, and pass
            // in the converted property value.
            try {
              setter.invoke(component, methodArgs);
            catch (Exception e) {
              System.err.println("Can't set property: " + name);
            }

            // Now go on to next command-line arg
            continue nextarg;
          }
        }

        // If we get here, we didn't find the named property
        System.err.println("Warning: No such property: " + name);
      }
    }

    return components;
  }
}
           
       
Related examples in the same category
1. Demonstrates how to get specific method information
2. How to set public field objects
3. Array Reflection: name and typeArray Reflection: name and type
4. Array Reflection: getComponentType()Array Reflection: getComponentType()
5. Array Reflection: create instanceArray Reflection: create instance
6. Array Reflection: get lengthArray Reflection: get length
7. Array Reflection: Multi Array Reflection
8. Class Reflection: is it an interfaceClass Reflection: is it an interface
9. Class Reflection: find out the constructor infomationClass Reflection: find out the constructor infomation
10. Class Reflection: field infomationClass Reflection: field infomation
11. Class Reflection: implemented interfaces
12. Class Reflection: show methodsClass Reflection: show methods
13. Class Reflection: class modifierClass Reflection: class modifier
14. Class Reflection: class nameClass Reflection: class name
15. Class Reflection: name for super classClass Reflection: name for super class
16. Object Reflection: get field valueObject Reflection: get field value
17. Object Reflection: set valueObject Reflection: set value
18. Object Reflection: create new instance
19. Object Reflection: invoke methodsObject Reflection: invoke methods
20. Object Reflection: invoke constructor with parametersObject Reflection: invoke constructor with parameters
21. Using reflection to show all the methods of a class,
22. Constructor ReflectionConstructor Reflection
23. Method ReflectionMethod Reflection
24. Field ReflectionField Reflection
25. Load a method on the flyLoad a method on the fly
26. Class reflectionClass reflection
27. Invoke method through Java Reflection APIInvoke method through Java Reflection API
28. Using reflection to check array type and lengthUsing reflection to check array type and length
29. Using reflection to create, fill, and display an arrayUsing reflection to create, fill, and display an array
30. This class shows using Reflection to get a field from another classThis class shows using Reflection to get a field from another class
31. Show the class keyword and getClass() method in actionShow the class keyword and getClass() method in action
32. Simple Demonstration of a ClassLoader WILL NOT COMPILE OUT OF THE BOX
33. Demonstrate classFor to create an instance of an object
34. CrossRef prints a cross-reference about all classes named in argv
35. Make up a compilable version of a given Sun or other API
36. Show a couple of things you can do with a Class object
37. Reflect1 shows the information about the class named in argv
38. Show that you can, in fact, take the class of a primitive
39. Show the PackagesShow the Packages
40. JavaP prints structural information about classes
41. This class is just here to give us something to work on, with a println()call that will prove we got here
42. Show loading a class and finding and calling its Main methodShow loading a class and finding and calling its Main method
43. Object InspectorObject Inspector
44. Reflection and XML
45. Get Color
46. Provides a set of static methods that extend the Java metaobject
47. All Fields Snippet
w_w_w_.ja__v_a2___s___._c___o_m__ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.