mat*_*tsa 4 java jpa java-8 glassfish-4 java-ee-7
我在Java 8中实现了一个复制构造函数,并使用它:
User user = // some object
LOG.debug("{}", user);
this.userAccount = new User(user);
LOG.debug("{}", this.userAccount);
Run Code Online (Sandbox Code Playgroud)
输出:
User@2799061
User@2799061
Run Code Online (Sandbox Code Playgroud)
这是同一个对象!怎么会这样?这是某种我没有意识到的最优化吗?
此外,我的"用户"类是JPA管理实体.这会以某种方式干涉吗?
这是同一个对象!
不,不是.当您使用LOG.debug方法时,它只会产生相同的输出.如果LOG.debug正在使用toString,则表示它具有相同的字符串结果toString.这可能是因为您的实现toString,或者可能是因为该对象具有相同的哈希码,因为标准Object#toString输出类名,@然后是十六进制的哈希码.有关详细信息,请参阅Object#toString Javadoc,但基本上:
toString
method for classObjectreturns a string consisting of the name of the class of which the object is an instance, the at-sign character@',以及对象哈希码的无符号十六进制表示.换句话说,此方法返回一个等于值的字符串:Run Code Online (Sandbox Code Playgroud)getClass().getName() + '@' + Integer.toHexString(hashCode())
你的头衔:
可以在同一个实例中实现Java拷贝构造函数结果吗?
不,不是Java.