1 38 package com.gargoylesoftware.htmlunit.html; 39 40 import com.gargoylesoftware.htmlunit.ObjectInstantiationException; 41 42 import java.lang.reflect.Constructor ; 43 import java.lang.reflect.InvocationTargetException ; 44 import java.util.Map ; 45 import java.util.HashMap ; 46 47 import org.xml.sax.Attributes ; 48 49 60 class DefaultElementFactory implements IElementFactory { 61 62 private static final Class [] CONSTRUCTOR_ARGS = new Class []{HtmlPage.class, Map .class}; 63 64 private final Constructor constructor_; 65 66 70 public DefaultElementFactory(final Class elementClass) { 71 72 if(!HtmlElement.class.isAssignableFrom(elementClass)) { 73 throw new ClassCastException (elementClass+" is not a subclass of "+HtmlElement.class); 74 } 75 try { 76 constructor_ = elementClass.getConstructor(CONSTRUCTOR_ARGS); 77 } 78 catch (final Exception e) { 79 throw new ObjectInstantiationException("required constructor not found in "+elementClass, e); 80 } 81 } 82 83 89 public HtmlElement createElement( 90 final HtmlPage page, final String tagName, final Attributes attributes) { 91 92 try { 93 Map attributeMap = null; 94 if(attributes != null) { 95 attributeMap = new HashMap (attributes.getLength()); 96 for(int i=0; i < attributes.getLength(); i++) { 97 attributeMap.put(attributes.getLocalName(i), attributes.getValue(i)); 98 } 99 } 100 final HtmlElement element = (HtmlElement)constructor_.newInstance(new Object []{page, attributeMap}); 101 return element; 102 } 103 catch( final IllegalAccessException e) { 104 throw new ObjectInstantiationException( 105 "Exception when calling constructor ["+constructor_+"]", e); 106 } 107 catch( final InstantiationException e ) { 108 throw new ObjectInstantiationException( 109 "Exception when calling constructor ["+constructor_+"]", e); 110 } 111 catch( final InvocationTargetException e ) { 112 throw new ObjectInstantiationException( 113 "Exception when calling constructor ["+constructor_+"]", e.getTargetException()); 114 } 115 } 116 } 117 | Popular Tags |