Skip to content

Commit ee8dd3a

Browse files
committed
Context: allow multi-injection in non-strict mode
With scijava.context.strict set to false (i.e.: strict=false flag of the Context), injecting an object multiple times is now allowed. This avoids the dreaded "Context already injected" exception which is thrown, for example, when reusing an op with a second module. This commit is dedicated to Christian Dietz!
1 parent 6db9fe0 commit ee8dd3a

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)