3

Is it possible to achieve such an assignment. The article here deals with private static field members but it does not help in this case as final members cannot be assigned.

Justification for using private static final as a qualifier for the member:

  • The data member is a ServiceClient so it makes sense to have it attached to type as it does not depend on the instance. Its thread safe too, so it will improve performance as I will not initialize the client for each instance.
  • The service client itself is a bean, having singleton scope. Hence actually there is only one instance. Since there will always be one instance, there is no point in allowing reassignment.
  • Since this client is only be used by methods of this class, it is private.

I am not exactly sure if this is an anti-pattern, but if it is then do my justification qualify to use it? If yes, then how can it be done. If no, then please suggest an alternative (and I would still be interested to know how can this be achieved, just for knowledge purposes).

Aman Deep Gautam
  • 8,091
  • 21
  • 74
  • 130
  • If you don't initialize a `final` member on the spot or in a constructor, you can't mark it as final - that's Java programming language design, sorry. A similar case are CDI injections, where the injected fields are often package private (and not final either) to make injection for unit tests possible w/o using setters. – Smutje Aug 12 '14 at 15:23
  • You can use reflection on the class along with reflection on the `Field` class itself for that field to remove its `final` modifier. Check out [this question here](http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection) for the nitty gritty. – Matt Aug 13 '14 at 04:00

1 Answers1

2

What you are trying to do, is not at all possible.

The most fundamental reason is that Java replaces static final "variable" occurrences in the code with the actual values (since it's of course known at compile time). Check out this SO answer for more details.

Even if you don't use final, Spring still won't allow you to inject a value into the static variable directly. You would have to use a setter like:

@Value("${my.name}")
public void setPrivateName(String privateName) {
    Sample.name = privateName;
}  

Check out this SO answer for more.

Community
  • 1
  • 1
geoand
  • 60,071
  • 24
  • 172
  • 190