1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jexl3.internal.introspection;
18
19 import java.beans.IntrospectionException;
20 import java.lang.reflect.Constructor;
21 import java.lang.reflect.InvocationTargetException;
22 import org.apache.commons.jexl3.JexlException;
23 import org.apache.commons.jexl3.introspection.JexlMethod;
24
25
26
27
28 public final class ConstructorMethod implements JexlMethod {
29
30 private final Constructor<?> ctor;
31
32
33
34
35
36
37
38
39 public static ConstructorMethod discover(final Introspector is, final Object ctorHandle, final Object... args) {
40 String className;
41 Class<?> clazz = null;
42 if (ctorHandle instanceof Class<?>) {
43 clazz = (Class<?>) ctorHandle;
44 className = clazz.getName();
45 } else if (ctorHandle != null) {
46 className = ctorHandle.toString();
47 } else {
48 return null;
49 }
50 final Constructor<?> ctor = is.getConstructor(clazz, new MethodKey(className, args));
51 if (ctor != null) {
52 return new ConstructorMethod(ctor);
53 }
54 return null;
55 }
56
57
58
59
60 ConstructorMethod(final Constructor<?> theCtor) {
61 this.ctor = theCtor;
62 }
63
64 @Override
65 public Object invoke(final Object obj, final Object... params) throws Exception {
66 final Class<?> ctorClass = ctor.getDeclaringClass();
67 boolean invoke = true;
68 if (obj != null) {
69 if (obj instanceof Class<?>) {
70 invoke = ctorClass.equals(obj);
71 } else {
72 invoke = ctorClass.getName().equals(obj.toString());
73 }
74 }
75 if (invoke) {
76 return ctor.newInstance(params);
77 }
78 throw new IntrospectionException("constructor resolution error");
79 }
80
81 @Override
82 public Object tryInvoke(final String name, final Object obj, final Object... args) {
83
84 if (ctor.getParameterCount() > 0 || args.length == 0) {
85 try {
86 final Class<?> ctorClass = ctor.getDeclaringClass();
87 boolean invoke = true;
88 if (obj != null) {
89 if (obj instanceof Class<?>) {
90 invoke = ctorClass.equals(obj);
91 } else {
92 invoke = ctorClass.getName().equals(obj.toString());
93 }
94 }
95 invoke &= name == null || ctorClass.getName().equals(name);
96 if (invoke) {
97 return ctor.newInstance(args);
98 }
99 } catch (InstantiationException | IllegalArgumentException | IllegalAccessException xinstance) {
100 return Uberspect.TRY_FAILED;
101 } catch (final InvocationTargetException xinvoke) {
102 throw JexlException.tryFailed(xinvoke);
103 }
104 }
105 return Uberspect.TRY_FAILED;
106 }
107
108 @Override
109 public boolean tryFailed(final Object rval) {
110 return rval == Uberspect.TRY_FAILED;
111 }
112
113 @Override
114 public boolean isCacheable() {
115 return true;
116 }
117
118 @Override
119 public Class<?> getReturnType() {
120 return ctor.getDeclaringClass();
121 }
122
123 }