1 package net.sourceforge.jparam.conversion.creators;
2
3 import java.util.Arrays;
4
5 import net.sourceforge.jparam.JParamException;
6
7 public abstract class AbstractCreator implements ICreator {
8 Class returnType;
9
10 Class[] parameterTypes;
11
12 public Class getReturnClass() {
13 return returnType;
14 }
15
16 public Class[] getParameterTypes() {
17 return parameterTypes;
18 }
19
20 public Object create(Object[] parameters) throws JParamException {
21 if (!canCreate(parameters)) {
22 throw new RuntimeException("Cannot create object: "
23 + returnType.getName() + " from: " + parameters);
24 }
25
26 try {
27 return internalCreate(parameters);
28 } catch (JParamException e) {
29 throw e;
30 } catch (Exception e) {
31 throw new JParamException(
32 "Unexpected exception when executing creator: " + this, e);
33 }
34 }
35
36 protected abstract Object internalCreate(Object[] parameters)
37 throws Exception;
38
39 protected abstract boolean creatorEquals(ICreator o);
40
41 public boolean canCreate(Object[] parameters) {
42 if (parameters.length != parameterTypes.length) {
43 return false;
44 }
45 for (int i = 0; i < parameters.length; i++) {
46 if (parameters[i] != null
47 && !parameterTypes[i].isAssignableFrom(parameters[i]
48 .getClass())) {
49 return false;
50 }
51 }
52 return true;
53 }
54
55 public String toString() {
56 return "Creator for: " + returnType.getName()
57 + " with argument types: " + Arrays.asList(parameterTypes);
58 }
59
60 public boolean equals(Object obj) {
61 if (!obj.getClass().equals(this.getClass())) {
62 return false;
63 }
64
65 AbstractCreator other = (AbstractCreator) obj;
66
67 if (!returnType.equals(other.returnType)) {
68 return false;
69 }
70 if (!Arrays.equals(parameterTypes, other.parameterTypes)) {
71 return false;
72 }
73
74 return creatorEquals(other);
75 }
76 }