Nathan Schwermann
Nathan Schwermann

Reputation: 31503

Howto set immutable field

  private static final Class<? extends UserManager> type;

  private static void setType(final Class <? extends UserManager> theType){
      if(type == null) type = theType;
      else throw new IllegalStateException("Type already set.");
  }

I want to get something like the above to work but it won't compile because type isn't final anyone know how to do this in Java? Is it possible?

Upvotes: 0

Views: 246

Answers (2)

Sergii Zagriichuk
Sergii Zagriichuk

Reputation: 5399

By default it is impossible, BUT using reflection :) all will be possible

      Field modifiersField = Field.class.getDeclaredField("modifiers");
      modifiersField.setAccessible(true);
      modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

      field.set(null, newValue);

Upvotes: 0

SLaks
SLaks

Reputation: 887767

This is intrinsically impossible.
final means that you cannot change it after initialization is complete.

Upvotes: 2

Related Questions