Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Java Tip 57: Applet parameterization via class reflection

Making applets configurable from HTML docs can be a chore -- unless you know how to do it the easy way

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 2 of 3

Note that it is harmless to have public fields that don't have corresponding HTML settings -- our method will simply ignore them.

Requiring public access to the parameter fields may seem to go against the object-oriented programming principle of encapsulation, but applets are very rarely accessed by anything other than a browser, and they are not often subclassed. So there isn't much danger that these fields will be misused. But if you absolutely want to encapsulate your applet, there is a slightly less elegant version of our technique that you can use. We'll see this in the section "Setting private fields".

Using the parameter fetching method

Here's all you have to write to get your applet initialized:

    public void init(){ 
        Util.initializeApplet(this, null); 
    } 


I declared initializeApplet() as a static method in class Util. Of course, it's up to you to declare it in your favorite utility class.

Implementation of the parameter fetching method

Now that you know how to use the parameter fetching method, here's the code for implementing it:

import java.applet.*;
import java.lang.reflect.*;
public abstract class Util {
    /**
     * Initializes an Applet's public non-final fields whose names start
     * with a given filter prefix.  The initial values will be read from
     * the HTML PARAM tags. 
     *
     * @param applet the applet to initialize.
     * @param filterPrefix only fields whose name starts with this prefix
     *        will be initialized.
     *        If the prefix is null, all public non-final fields 
     *        will be initialized
     */
    public static void initializeApplet(Applet applet, String filterPrefix) {
        Class metaclass = applet.getClass();
        Field[] fields = metaclass.getFields();
        String param = null;
        for (int i = 0; i < fields.length; i++) {
            try {
                param = applet.getParameter(fields[i].getName());
                if (param == null ||
                    Modifier.isFinal(fields[i].getModifiers()) ||                
                    ((filterPrefix != null) && 
                     !fields[i].getName().startsWith(filterPrefix))
                   )                
                   continue;            
                Class fieldType = fields[i].getType();
                if (fieldType.equals(boolean.class)) {
                    fields[i].setBoolean(applet, Boolean.valueOf(param).booleanValue());
                }
                else if (fieldType.equals(byte.class)) {
                    fields[i].setByte(applet, Byte.valueOf(param).byteValue());
                }
                else if (fieldType.equals(char.class)) {
                    fields[i].setChar(applet, param.charAt(0));
                }
                else if (fieldType.equals(double.class)) {
                    fields[i].setDouble(applet, Double.valueOf(param).doubleValue());
                }
                else if (fieldType.equals(float.class)) {
                    fields[i].setFloat(applet, Float.valueOf(param).floatValue());
                }
                else if (fieldType.equals(int.class)) {
                    fields[i].setInt(applet, Integer.valueOf(param).intValue());
                }
                else if (fieldType.equals(long.class)) {
                    fields[i].setLong(applet, Long.valueOf(param).longValue());
                }
                else if (fieldType.equals(short.class)) {
                    fields[i].setShort(applet, Short.valueOf(param).shortValue());
                }
 
                else if (fieldType.equals(String.class)) {
                    fields[i].set(applet, param);
                }
            }
            catch (Exception e) {
                System.err.println(e + " while initializing " + fields[i]);
            }
        }
    }
}


We consider every public field in the applet as a potential parameter, settable with some PARAM tag. So, we try to match each public field with a corresponding PARAM tag. If there is a match, we fetch the corresponding value.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comment
Login
Forgot your account info?
Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources
  • For information on class reflection, see Chuck McManis's JavaWorld article, "Take an in-depth look at the Java Reflection API" http://www.javaworld.com/javaworld/jw-09-1997/jw-09-indepth.html