Spring中引用传递的问题
public class Apple
{
private boolean isJuicy;
private boolean isRipe;
public Apple(boolean isJuicy)
{
isJuicy = isJuicy;
}
public void setRipe(boolean ripe)
{
this.isRipe = ripe;
}
public boolean isRipe()
{
return this.isRipe;
}
}
在 Spring 中,我有两个服务类 AppleService
& FruitService
。
AppleService
public Apple createApple(boolean isJuicy)
{
Apple apple = null;
apple = new Apple(isJuicy);
fruitService.saveApple(apple);
log("ripe:" + apple.isRipe()); // false
return apple;
}
FruitService
public void saveApple(Apple apple)
{
if(apple.isJuicy())
apple.setRipe(true);
persist(apple);
log("ripe:" + apple.isRipe()); // true
}
为什么在 FruitService
中报告 Apple 已经成熟,但在 AppleService
中却没有报告?
我认为它通过引用 FruitService
传递的事实保证了 AppleService 中的 apple
对象中应该存在相同的对象和对象属性?
public class Apple
{
private boolean isJuicy;
private boolean isRipe;
public Apple(boolean isJuicy)
{
isJuicy = isJuicy;
}
public void setRipe(boolean ripe)
{
this.isRipe = ripe;
}
public boolean isRipe()
{
return this.isRipe;
}
}
In Spring I have two service classes AppleService
& FruitService
.
AppleService
public Apple createApple(boolean isJuicy)
{
Apple apple = null;
apple = new Apple(isJuicy);
fruitService.saveApple(apple);
log("ripe:" + apple.isRipe()); // false
return apple;
}
FruitService
public void saveApple(Apple apple)
{
if(apple.isJuicy())
apple.setRipe(true);
persist(apple);
log("ripe:" + apple.isRipe()); // true
}
Why is the Apple reported as being ripe in the FruitService
but not in the AppleService
?
I thought the fact that it is passed by reference to the FruitService
guarantees that the same object and object properties should be present in the apple
object in the AppleService?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管我同意对该问题的评论(您需要发布更多代码),但我确信这里的核心问题是,Java从不通过引用传递。它传递原始值的原始值,并传递对象的“对象引用”(基本上是指针)。
在Java中,当你获取一个作为参数传递的对象时,调用该对象的方法将影响传递的原始对象。但实际上为对象赋值不会影响传递的对象,而是将引用(也称为指针)设置为新对象。
此处对此进行了更好的解释。您可能还想查看这个 StackOverflow 问题。
Though I agree with the comments on the question (you need to post more code), I'm sure the core issue here is that, well, Java is never pass-by-reference. It passes primitive values for primitive values, and it passes "object references" (which are basically pointers) for objects.
In Java, when you get an object passed as a parameter, calling methods on the object will affect the original object passed. But actually assigning a value to the object will not affect the object passed, instead you'll set the reference (aka pointer) to a new object.
This is better explained here. You may also want to look at this StackOverflow question.
我认为问题是这样的:当 isJuicy 作为 true 传入时,您没有在构造函数中将 isRipe 设置为 true 。在 java 中,未设置的布尔值的默认值为 false。
这将解决这个问题:
private boolean isRipe;
I think the problem is this: you aren't setting isRipe to true in the constructor when isJuicy is passed in as true. In java, the default value for an unset boolean is false.
This will fix it:
private boolean isRipe;