xiaodududu / google-guice

Automatically exported from code.google.com/p/google-guice
Apache License 2.0
0 stars 0 forks source link

Dynamically passing key to @Named annotation #654

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Hi,

2 pieces of same code behaving differently. Could any one help understand why 
is it so?

1.This works without any compilation issues,
  private final String var ="US";
  @Inject @Named (var) private Validator validator; 

2.This is giving compilation errors,
  Compilation Error:"The value for annotation attribute Named.value  must be a constant expression"
  private final String var =System.getProperty("US");
  @Inject @Named (var) private Validator validator; 

Thanks
Matt

Original issue reported on code.google.com by sony....@gmail.com on 16 Sep 2011 at 9:41

GoogleCodeExporter commented 9 years ago
Two pieces of different code behaving differently. :-)

What may be happening behind the scenes is "US" is being inlined and the 
compiler knows it can never change.  Annotations are effectively static 
modifiers, so I'm surprised the first example even compiles.  I bet making 
'var' static may fix the second one, but even then I'm not entirely sure.  

Original comment by sberlin on 16 Sep 2011 at 10:05

GoogleCodeExporter commented 9 years ago
(FWIW, this is a quirk with the annotations subsystem and java and is nothing 
specific to Guice.)

Original comment by sberlin on 16 Sep 2011 at 10:05

GoogleCodeExporter commented 9 years ago
Adding static gives the same compilation error. 
Do you have any thoughts to make the second scenario work?

Original comment by sony....@gmail.com on 16 Sep 2011 at 10:18

GoogleCodeExporter commented 9 years ago
Probably not gonna work at all -- javac wants to know the value, it's not going 
to let you change it at runtime.  You can ask on stackoverflow, but I suspect 
that'll be the answer.

Original comment by sberlin on 16 Sep 2011 at 10:42

GoogleCodeExporter commented 9 years ago
You can construct the Key<String> at runtime and use the Injector directly, or 
call getProvider(key) inside a module.

Original comment by isaac.q....@gmail.com on 17 Sep 2011 at 2:09