Skip to content

Commit d84ab12

Browse files
committed
Merge pull request #216 from scijava/non-strict-injection
Allow context multi-injection in non-strict mode
2 parents 955b22c + ee8dd3a commit d84ab12

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/main/java/org/scijava/Context.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -436,7 +436,7 @@ private void inject(final Field f, final Object o) {
436436
final Class<?> type = f.getType();
437437
if (Service.class.isAssignableFrom(type)) {
438438
final Service existingService = (Service) ClassUtils.getValue(f, o);
439-
if (existingService != null) {
439+
if (strict && existingService != null) {
440440
throw new IllegalStateException("Context already injected: " +
441441
f.getDeclaringClass().getName() + "#" + f.getName());
442442
}
@@ -450,14 +450,24 @@ private void inject(final Field f, final Object o) {
450450
throw new IllegalArgumentException(
451451
createMissingServiceMessage(serviceType));
452452
}
453+
if (existingService != null && existingService != service) {
454+
// NB: Can only happen in non-strict mode.
455+
throw new IllegalStateException("Mismatched context: " +
456+
f.getDeclaringClass().getName() + "#" + f.getName());
457+
}
453458
ClassUtils.setValue(f, o, service);
454459
}
455460
else if (Context.class.isAssignableFrom(type) && type.isInstance(this)) {
456461
final Context existingContext = (Context) ClassUtils.getValue(f, o);
457-
if (existingContext != null) {
462+
if (strict && existingContext != null) {
458463
throw new IllegalStateException("Context already injected: " +
459464
f.getDeclaringClass().getName() + "#" + f.getName());
460465
}
466+
if (existingContext != null && existingContext != this) {
467+
// NB: Can only happen in non-strict mode.
468+
throw new IllegalStateException("Mismatched context: " +
469+
f.getDeclaringClass().getName() + "#" + f.getName());
470+
}
461471

462472
// populate Context parameter
463473
ClassUtils.setValue(f, o, this);

0 commit comments

Comments
 (0)