Immutability after dependency injection, initialization

I would like to be able to indicate that the member variables of an object are immutable after the object has been “initialized”, which for me means that after it has been added with any dependencies, and performed any other initialization operations that it can perform only after DI.

Are there languages ​​that satisfy my interest - formalize DI, initialization, and maintain immutability in this way? Maybe it's stupid to make them part of the language; probably no. I'm not sure.

Today I program in Java, but I can’t use "final" almost as much as I want, because these phases occur after the constructor has completed execution. Any tips on how to get what I want using Java? I assume that my objects can implement the base class so that these phases happen before the constructor finishes, or use aspects to do the same.

Thoughts?

+5
source share
5 answers

, , . (, , ), , factory, - .

, , , . String ( -). , , .

+3

:

  • builder/ factory - , , . , , "mutator", . Spring FactoryBean .

  • MutableObject, . - - , , .

Spring -, Spring - . factory beans, beans, factory-method/factory-bean bean, Spring .

spring. Spring bean, . seal(), - . BeanFactoryPostProcessor, , , init-method = "seal". bean.

+4

Java builder, , .

Scala, .

+1

Java, mutator , , ( ), , .

public void setMyProperty(String newValue) {
   checkInitialized();
   myProperty = newValue;
}

public void checkInitialized() {
   if ( initialized ) {
      throw new IllegalStateException("Setter called after initialization");
   }
}

, . , .

0

, , @Immutable.

Javadoc .

Findbugs Eclipse.

@Alexander:

As I understand it, he asked how to indicate that the class is immutable. Not how to write an immutable class. This annotation can give you tool support to make sure you don't have an error in your class that you think is immutable.

Excerpt from Javadoc:

If necessary, this means that all public fields are final and that all public final referenced fields relate to other immutable objects

0
source

All Articles