Skip to content

Commit 567269d

Browse files
committed
Add a smart "typed null" placeholder
This 'Nil' object knows its generic type at runtime, and can generate proxy objects which implement the interfaces of that type, with customizable behavior per interface method via callbacks. The term 'nil' was chosen, despite lots of possibility for confusion with related paradigms such as the Scala language, because it is very short while loosely meaning the same thing as 'null', 'None', etc.
1 parent 615e027 commit 567269d

2 files changed

Lines changed: 214 additions & 0 deletions

File tree

‎pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,12 @@
115115
<artifactId>scijava-common</artifactId>
116116
</dependency>
117117

118+
<!-- Third-party dependencies -->
119+
<dependency>
120+
<groupId>com.google.guava</groupId>
121+
<artifactId>guava</artifactId>
122+
</dependency>
123+
118124
<!-- Test scope dependencies -->
119125
<dependency>
120126
<groupId>junit</groupId>
Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
/*
2+
* #%L
3+
* SciJava Operations: a framework for reusable algorithms.
4+
* %%
5+
* Copyright (C) 2016 - 2019 SciJava Ops developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.ops.types;
31+
32+
import com.google.common.reflect.TypeToken;
33+
34+
import java.lang.reflect.InvocationHandler;
35+
import java.lang.reflect.Method;
36+
import java.lang.reflect.ParameterizedType;
37+
import java.lang.reflect.Proxy;
38+
import java.lang.reflect.Type;
39+
import java.lang.reflect.TypeVariable;
40+
import java.util.Set;
41+
42+
import org.scijava.util.Types;
43+
44+
/**
45+
* A "typed null" which knows its generic type, and can generate proxy objects
46+
* implementing that type's interfaces, with customizable behavior per interface
47+
* method via callbacks.
48+
* <p>
49+
* The term "nil" was chosen, despite lots of possibility for confusion with
50+
* related paradigms such as the Scala language, because it is very short while
51+
* loosely meaning the same thing as {@code null}, {@code None}, etc.
52+
* </p>
53+
*
54+
* @author Curtis Rueden
55+
*/
56+
public abstract class Nil<T> implements GenericTyped, Proxyable<T>,
57+
InvocationHandler
58+
{
59+
60+
/** Generic type of the object. */
61+
private final TypeToken<?> typeToken;
62+
63+
/** An object which holds any method callbacks. */
64+
private final Object callbacks;
65+
66+
/**
67+
* Creates a new {@code Nil} whose generic type (returned by
68+
* {@link #getType()}) is the one specified by the generic parameters used at
69+
* construction.
70+
* <p>
71+
* For example:
72+
* </p>
73+
*
74+
* <pre>
75+
*
76+
* Nil&lt;List&lt;Map&lt;K, V&gt;&gt;&gt; nil = new Nil&lt;List&lt;Map&lt;K, V&gt;&gt;&gt;() {};
77+
* </pre>
78+
* <p>
79+
* Subsequent calls to {@code nil.getType()} will return the proper
80+
* generically typed result&mdash;in the above example, a
81+
* {@link ParameterizedType} whose raw type is {@code List}, and whose single
82+
* type parameter is a {@link ParameterizedType} with raw type of {@code Map}
83+
* and {@link TypeVariable} type parameters of {@code K} and {@code V}
84+
* respectively, including their bounds inferred by the compiler in the
85+
* context where the expression was written.
86+
* </p>
87+
*/
88+
public Nil() {
89+
typeToken = new TypeToken<T>(getClass()) {};
90+
callbacks = this;
91+
}
92+
93+
public Nil(final Object callbacks) {
94+
typeToken = new TypeToken<T>(getClass()) {};
95+
this.callbacks = callbacks(callbacks);
96+
}
97+
98+
/**
99+
* Creates a {@code Nil} wrapping the given generic {@link Type}.
100+
* <p>
101+
* This method is intentionally private; use {@link Nil#of(Type)} to create
102+
* such a {@code Nil} from calling code.
103+
* </p>
104+
*/
105+
private Nil(final Type type) {
106+
typeToken = TypeToken.of(type);
107+
callbacks = this;
108+
}
109+
110+
/**
111+
* Creates a {@code Nil} wrapping the given generic {@link Type}, and
112+
* possessing the specified method callbacks.
113+
* <p>
114+
* This method is intentionally private; use {@link Nil#of(Type, Object)} to
115+
* create such a {@code Nil} from calling code.
116+
* </p>
117+
*/
118+
private Nil(final Type type, final Object callbacks) {
119+
typeToken = TypeToken.of(type);
120+
this.callbacks = callbacks(callbacks);
121+
}
122+
123+
// -- Static utility methods --
124+
125+
/**
126+
* Creates a {@code Nil} of the given generic {@link Type}, with no extra
127+
* method callbacks.
128+
*/
129+
public static Nil<?> of(final Type type) {
130+
return new Nil<Object>(type) {};
131+
}
132+
133+
/**
134+
* Creates a {@code Nil} of the given {@link Type}, with extra method
135+
* callbacks contained in the specified object.
136+
*/
137+
public static Nil<?> of(final Type type, final Object callbacks) {
138+
return new Nil<Object>(type, callbacks) {};
139+
}
140+
141+
// -- Object methods --
142+
143+
@Override
144+
public String toString() {
145+
return typeToken.toString();
146+
}
147+
148+
// -- GenericTyped methods --
149+
150+
@Override
151+
public Type getType() {
152+
return typeToken.getType();
153+
}
154+
155+
// -- GenericProxy methods --
156+
157+
/**
158+
* Create a proxy which implements all the same interfaces as this object's
159+
* generic type.
160+
* <p>
161+
* CTR FIXME - write up how method delegation works.
162+
* </p>
163+
*/
164+
@Override
165+
public T proxy() {
166+
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
167+
168+
// extract the generic type's interfaces
169+
final Set<?> ifaceSet = typeToken.getTypes().interfaces().rawTypes();
170+
final boolean appendGT = !ifaceSet.contains(GenericTyped.class);
171+
final int ifaceCount = ifaceSet.size() + (appendGT ? 1 : 0);
172+
final Class<?>[] interfaces = new Class<?>[ifaceCount];
173+
ifaceSet.toArray(interfaces);
174+
if (appendGT) interfaces[ifaceCount - 1] = GenericTyped.class;
175+
176+
// NB: Technically, this cast is not safe, because T might not be
177+
// an interface, and thus might not be one of the proxy's types.
178+
@SuppressWarnings("unchecked")
179+
final T proxy = (T) Proxy.newProxyInstance(loader, interfaces, this);
180+
return proxy;
181+
}
182+
183+
// -- InvocationHandler methods --
184+
185+
@Override
186+
public Object invoke(final Object proxy, final Method method,
187+
final Object[] args) throws Throwable
188+
{
189+
try {
190+
// Look for a Nil subclass method of the same signature.
191+
final Method m = callbacks.getClass().getMethod(method.getName(), //
192+
method.getParameterTypes());
193+
return m.invoke(callbacks, args);
194+
}
195+
catch (final NoSuchMethodException exc) {
196+
// NB: Default behavior is to do nothing and return null.
197+
return Types.nullValue(method.getReturnType());
198+
}
199+
}
200+
201+
// -- Helper methods --
202+
203+
/** Unwraps the given callbacks object. */
204+
private Object callbacks(final Object o) {
205+
return o instanceof Nil ? ((Nil<?>) o).callbacks : o;
206+
}
207+
208+
}

0 commit comments

Comments
 (0)