4.0: Unexpected behavior with bindConstant: Empty string injected to String.class without explicit binding
- Dominant language
- Java
- Stars
- 12.7k
- Forks
- 1.7k
- Avg merge
- 11m
- Merged PRs (30d)
- 2
Description
I'm seeing Guice inject an empty string to String.class parameters even without an explicit binding if I have declared a bindConstant() to a named string with a string value. It doesn't happen with other types, like Integer, and is pretty unexpected behavior.
Minimal reproduction is below.
Guice module:
```
public class FancyGuiceModule implements Module {
public void configure(Binder binder) {
binder.bindConstant()
.annotatedWith(Names.named("fancy_name"))
.to("fancy_value");
}
}
```
Injected class:
```
public class NotFancyPojo {
private final String notFancy;
@Inject
NotFancyPojo(String notFancy) {
this.notFancy = notFancy;
}
String getNotFancy() {
return notFancy;
}
}
```
And the test:
```
public class FancyTest {
@Test
public void testThingTest() {
Injector injector =
Guice.createInjector(new FancyGuiceModule());
NotFancyPojo sp = injector.getInstance(NotFancyPojo.class);
System.out.println("inj: " + sp.getNotFancy() + "; " + sp.getNotFancy().getClass().getName() + "\n");
}
}
```
I expected the test to blow up by raising an exception because I haven't bound anything to String.class (this is a simplified version of a larger test I wrote expected the failing behavior) and was surprised when it didn't. Instead, it outputs:
```
inj: ; java.lang.String
```
The only note about this I could find was here:
https://google.github.io/guice/api-docs/4.0/javadoc/com/google/inject/Binder.html#bindConstant--
Which says:
> Sets up a constant binding. Constant injections must always be annotated. When a constant binding's value is a string, it is eligile for conversion to all primitive types, to all enums, and to class literals. Conversions for other types can be configured using convertToTypes().
Which doesn't seem to imply this behavior.
Contributor guide
Assessment
This issue has not been assessed yet.