jcabi-aspects icon indicating copy to clipboard operation
jcabi-aspects copied to clipboard

@Immutable does not work as expected

Open simonjenga opened this issue 9 years ago • 3 comments

The com.jcabi.aspects.@Immutable annotates an immutable class. As soon as you try to instantiate this class a runtime exception will be thrown, because this class is mutable.

However, the following code does not throw any runtime exception as stated in the above documentation.

import com.jcabi.aspects.Immutable;

@Immutable
public class JcabiImmutable {

    private int age;

    public JcabiImmutable(int age) {
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }

    public static void main(String[] args) {
        JcabiImmutable jImmutable = new JcabiImmutable(15);
        System.out.println(jImmutable.getAge());
    }
}

Any reasons that can explain this? What is the motivation behind throwing runtime exception?

The java.lang.String is also immutable but doesn't throw any runtime exception when you try to create an instance of it.

simonjenga avatar Dec 21 '15 20:12 simonjenga

@yegor256 please pay attention to this issue (par.21)

dmarkov avatar Dec 25 '15 09:12 dmarkov

@simonjenga this code will throw an exception, if you weave it using AspectJ, more info here: http://aspects.jcabi.com/example-weaving.html

yegor256 avatar Dec 25 '15 10:12 yegor256

@yegor256 Unfortunately, it doesn't throw an exception. I created a simple maven standalone project to test the class and here is the output:

./MavenStandalone>mvn compile exec:java
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building maven-standalone 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ maven-standalone ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ maven-standalone ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- exec-maven-plugin:1.4.0:java (default-cli) @ maven-standalone ---
15
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

It prints 15 which is not what i expect :(

simonjenga avatar Dec 26 '15 09:12 simonjenga