1 33 package net.sf.jga.fn.property; 34 35 import java.lang.reflect.Constructor ; 36 import java.lang.reflect.InvocationTargetException ; 37 import java.text.MessageFormat ; 38 import net.sf.jga.fn.EvaluationException; 39 import net.sf.jga.fn.Generator; 40 41 49 50 public class ConstructDefault<R> extends Generator<R> { 51 52 static final long serialVersionUID = 9150185598879755334L; 53 54 private Class <R> _objclass; 55 56 private transient Constructor <R> _ctor; 57 58 65 66 public ConstructDefault(Class <R> ctorclass) { 67 if (ctorclass == null) { 68 String msg = "Class to be constructed must be specified"; 69 throw new IllegalArgumentException (msg); 70 } 71 72 Class [] argclasses = new Class [0]; 73 74 _objclass = ctorclass; 75 76 try { 77 _ctor = ctorclass.getConstructor(argclasses); 78 } 79 catch (NoSuchMethodException x) { 80 String msg = "No default constructor for class {0}"; 81 Object [] args = new Object []{_objclass.getName()}; 82 IllegalArgumentException x1 = 83 new IllegalArgumentException (MessageFormat.format(msg,args)); 84 x1.initCause(x); 85 throw x1; 86 } 87 } 88 89 92 public synchronized Constructor <R> getConstructor() throws NoSuchMethodException { 93 if (_ctor == null) 94 _ctor = _objclass.getConstructor(new Class [0]); 95 96 return _ctor; 97 } 98 99 104 public R gen() { 105 try { 106 R val = (R) getConstructor().newInstance(new Object [0]); 107 return val; 108 } 109 catch (NoSuchMethodException x) { 110 String msg = "No default constructor for class {0}"; 111 Object [] args = new Object []{_objclass.getName()}; 112 throw new EvaluationException(MessageFormat.format(msg,args), x); 113 } 114 catch (InstantiationException x) { 115 String msg = "class {0} is abstract: cannot be constructed"; 116 Object [] args = new Object []{_objclass.getName()}; 117 throw new EvaluationException(MessageFormat.format(msg,args), x); 118 } 119 catch (IllegalAccessException x) { 120 String msg = "default ctor in class {0} is not accessible"; 121 Object [] args = new Object []{_objclass.getName()}; 122 throw new EvaluationException(MessageFormat.format(msg,args), x); 123 } 124 catch (InvocationTargetException x) { 125 String msg = "default ctor in class {0} failed: "+x.getMessage(); 126 Object [] args = new Object []{_objclass.getName()}; 127 throw new EvaluationException(MessageFormat.format(msg,args), x); 128 } 129 } 130 131 135 public void accept(net.sf.jga.fn.Visitor v) { 136 if (v instanceof ConstructDefault.Visitor) 137 ((ConstructDefault.Visitor)v).visit(this); 138 else 139 v.visit(this); 140 } 141 142 144 public String toString() { 145 return "new "+_objclass.getName()+"()"; 146 } 147 148 150 154 public interface Visitor extends net.sf.jga.fn.Visitor { 155 public void visit(ConstructDefault host); 156 } 157 } 158 | Popular Tags |