01: package org.vraptor.component;
02:
03: import java.lang.reflect.Constructor;
04: import java.util.Calendar;
05: import java.util.Collection;
06: import java.util.GregorianCalendar;
07:
08: import org.vraptor.reflection.ReflectionUtil;
09:
10: /**
11: * Wrapper for reflecting on Class with generic functionalities.
12: *
13: * @author Guilherme Silveira
14: * @since 2.3.1
15: */
16: public class Clazz<T> {
17:
18: private final Class<T> type;
19:
20: public Clazz(Class<T> type) {
21: this .type = type;
22: }
23:
24: public Class<T> getType() {
25: return type;
26: }
27:
28: /**
29: * Creates a new instance from this type, using a default implementation of
30: * a collection when needed. If the type is a primitive, return its default value.
31: *
32: * @return the new instance
33: * @throws ComponentInstantiationException
34: */
35: public Object newInstance() throws ComponentInstantiationException {
36: if (this .type.isPrimitive()) {
37: if (this .type.equals(boolean.class)) {
38: return false;
39: } else if (this .type.equals(int.class)) {
40: return 0;
41: } else if (this .type.equals(long.class)) {
42: return 0L;
43: } else if (this .type.equals(double.class)) {
44: return 0d;
45: } else if (this .type.equals(short.class)) {
46: return (short) 0;
47: } else if (this .type.equals(float.class)) {
48: return 0f;
49: } else if (this .type.equals(char.class)) {
50: return (char) (0);
51: } else if (this .type.equals(byte.class)) {
52: return (byte) 0;
53: }
54: }
55: if (Calendar.class.isAssignableFrom(this .type)) {
56: return ReflectionUtil.instantiate(GregorianCalendar.class);
57: }
58: if (Collection.class.isAssignableFrom(this .type)) {
59: return ReflectionUtil.instantiateCollection(this .type);
60: }
61: return ReflectionUtil.instantiate(this .type);
62: }
63:
64: /**
65: * Returns the single constructor - if there is only one.
66: * @return the single constructor.
67: * @throws InvalidComponentException if there is more than one constructor.
68: */
69: public BeanConstructor findSingleConstructor()
70: throws InvalidComponentException {
71: Constructor[] constructors = type.getConstructors();
72: if (constructors.length != 1) {
73: throw new InvalidComponentException(
74: type.getName()
75: + " component has "
76: + constructors.length
77: + " accessible constructors. This is not desirable as it may reflect optional arguments and create complex attributes.");
78: }
79: return new ComponentConstructor(constructors[0]);
80: }
81:
82: }
|