【发布时间】:2015-08-21 21:35:55
【问题描述】:
我试图更好地理解 Java 变量作用域是如何工作的,以及当我们在方法中执行类似以下操作时底层数据究竟会发生什么:
this.variable = variable
这条线到底是做什么的?这是我的实际问题:
我正在加载位图以在我的 (Android) OpenGL ES 2.0 项目中应用为纹理。它是这样的:
public loadBitmapsForTextures(){
myBitmap = BitmapFactory.decodeResource(view.getResources(), R.drawable.testbmp, Options);
myObject.setTexture(view, myBitmap);
Log.v("NewTag","Recycled: Again: "+myBitmap);
myBitmap.recycle(); //All done - no longer required. But why is myBitmap still valid here?
}
在我的 Sprite 类(其中 myObject 是一个对象)中,我有以下内容:
public void setTexture(GLSurfaceView view, Bitmap imgTexture){
this.imgTexture=imgTexture; //What exactly is this line doing? Copying the actual data? Just making another 'pointer' to the original data?
iProgId = Utils.LoadProgram(strVShader, strFShader);
iBaseMap = GLES20.glGetUniformLocation(iProgId, "u_baseMap");
iPosition = GLES20.glGetAttribLocation(iProgId, "a_position");
iTexCoords = GLES20.glGetAttribLocation(iProgId, "a_texCoords");
//Return usable texture ID from Utils class
texID = Utils.LoadTexture(view, imgTexture);
Log.v("NewTag","Recycled: Before: "+imgTexture);
imgTexture.recycle();
imgTexture=null;
Log.v("NewTag","Recycled: After"+imgTexture);
}
setTexture 方法中的日志给出了我期望的结果。第一个为位图命名:
回收:之前:android.graphics.Bitmap@1111111
回收:之后:null
但是,初始 loadBitmapsForTextures() 方法中的日志语句给出了一些我没有预料到的东西:
回收:再次:android.graphics.Bitmap@1111111
为什么允许我(看似)再次回收此位图?我只能假设我对以下行的理解是有缺陷的:
this.imgTexture=imgTexture;
那么,这条线到底做了什么?据我所知,它将类变量应用到与局部变量相同的值(被传递到方法中),但是,显然还有更多事情正在发生。它真的会创建一个全新的位图吗?如果是这样,为什么登录时名称相同?
【问题讨论】:
-
什么都没有发生。你打电话给
recycle两次。看看你的代码。在setTexture内部调用imgTexture.recycle();,然后在loadBitmapsForTextures()内部调用myBitmap.recycle();。 -
@Max,是的,我知道,我是故意这样做的,这就是我要问的。如果我在 setTexture() 中回收位图,为什么它在 loadBitmapForTextures() 中仍然有效?干杯。
-
因为
myBitmap和imgTexture是指向同一个对象的两个独立变量。所以,当你说imgTexture = null这意味着imgTexture现在什么都没有。不,你在哪里告诉myBitmap指向任何内容,所以它仍然指向原始纹理。有意义吗?