How to create a persistent object in Java?

How to create a link to a permanent object?

final Myclass obj = new Myclass();

doesn’t work, he says that obj (link) should not be rewritten, but we can still change the related object.

I want to ensure that the object itself does not change after construction.

+4
source share
9 answers

Just make it immutable (e.g. Stringis). Or wrap it in another object that restricts access to the mutators of the object in question (for example, Collections.unmodifiableList()gophers).

+16
source

You mix two things: the final and the unchanging.

, ( ) (, , )

( , ), . - [] String.

+10

. Java , . , . BalusC, , .

+9
+1

Java , "", , "getter", . , , :

public class MyClass {
  String something;
  int somethingElse;

  // The class can only be modified by the constructor
  public MyClass(String something, int somethingElse) {
    this.something = something;
    this.somethingElse = somethingElse;
  }

  // Access "something".  Note that it is a String, which is immutable.
  public String getSomething() {
    return something;
  }

  // Access "somethingElse".  Note that it is an int, which is immutable.
  public int getSomethingElse() {
     return somethingElse;
  }
}
+1

, , .

final MyClass obj = new Myclass();

, obj . Java const, ++. MyClass ( MyClass {...}), .

0

.

final MyClass obj = new MyClass();
0

java , , . - , , .

0

, "" .

, "", . , :

  • get is
  • ( void )

Yes, getter methods can mutate an object. But if your code (or the code you use) does this, you have some big problems, please ask for help :)

the code:

class ImmutableWrapper
    public static <T> T wrap(T thing) {
        return (T) Proxy.newProxyInstance(thing.getClass().getClassLoader(), new Class[]{thing.getClass()}, OnlyGettersInvocationHandler.instance);
    }

    private static class OnlyGettersInvocationHandler implements InvocationHandler {
        public static InvocationHandler instance;
        @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            final String name = method.getName();
            if ((args == null || args.length == 0)
                    && (name.startsWith("get") || name.startsWith("is")
                    && !method.getReturnType().equals(Void.class))) {
                return method.invoke(proxy, args);
            } else {
                throw new UnsupportedOperationException("immutable object: " + proxy + ", cannot call " + name);
            }
        }
    }
}

SomeClass myThing = ... create and populate some object ...
SomeClass myImmutableThing = ImmutableWrapper.wrap(myThing);
myImmutableThing.setValue('foo');   // throws Exception
myImmutableThing.whatever();        // throws Exception
myImmutableThing.getSomething();    // returns something
myImmutableThing.isHappy();         // returns something
0
source

Source: https://habr.com/ru/post/1730212/


All Articles