[jdom-interest] Re: Factories for Element creation

Patrick Dowler Patrick.Dowler at nrc.ca
Wed Nov 1 09:50:01 PST 2000

On Wed, 01 Nov 2000, you wrote:
> Just to clarify...I'm not really talking about "special" elements that
> know
> something extra that can be gleaned by parsing, but rather app-specific
> overloaded elements that will information added to them after the fact,
> not
> at creation time.
> So, in fact, a "standard" SAXBuilder, etc., could just support no-arg
> constructors for custom "MyElement" style classes - assuming they are
> extensions of Element.  This eliminates the need for a factory, even, if
> one
> could just say "oh, by the way, when you construct a new element, make
> it:
> Class.forName( elementClass).newInstance(), and by default, elementClass
> is
> "org.jdom.Element".  Of course, this is assuming that all Element
> properties
> can be set in JavaBean style, and don't have to be passed in the
> constructor

This isn't actually true for Element: the name is set only by the constructor.
However, it is simple enough to find a Constructor that takes a single String
arg and use that to instantiate the Element subclass, so that doesn't stop one
from using this approach:

protected Element createElement(String name, String eClass)
                Class c = Class.forName( eClass ); // could be done once

                Class[] argTypes = new Class[1];   // once
                argTypes[0] = String.class;
                String[] args = new String[1];          // once
                args[0] = name; 
                Constructor ctor = c.getConstructor(argTypes);  // once

                return (Element) ctor.newInstance(args);


Patrick Dowler
Canadian Astronomy Data Centre

More information about the jdom-interest mailing list