在下面的例子中,'this'用于初始化sinstance
.
public class MyApplication extends Application { public static MyApplication sinstance; @Override public void onCreate() { super.onCreate(); sinstance=this; }
据我所知,'this'指的是对象的当前实例的引用.如果我错了,请纠正我.现在考虑以下程序
public static MyApplication sinstance; @Override public void onCreate() { super.onCreate(); sinstance=new MyApplication(); }
new MyApplication
用于实例化sinstance
.那么为什么第二个程序在运行时崩溃,而第一个程序不会产生任何错误.它给出以下错误:
12-16 17:56:09.559 2156-2156/compdom.sad E/art: Throwing OutOfMemoryError "Failed to allocate a 10439248 byte allocation with 5527284 free bytes and 5MB until OOM" 12-16 17:56:09.559 2156-2156/compdom.sad E/AndroidRuntime: Error reporting crash java.lang.OutOfMemoryError: Failed to allocate a 10439248 byte allocation with 5527284 free bytes and 5MB until OOM at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95) at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:125) at java.lang.StringBuffer.append(StringBuffer.java:278) at java.io.StringWriter.write(StringWriter.java:123) at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:358) at com.android.internal.util.FastPrintWriter.appendLocked(FastPrintWriter.java:303) at com.android.internal.util.FastPrintWriter.write(FastPrintWriter.java:625) at com.android.internal.util.FastPrintWriter.append(FastPrintWriter.java:658) at java.io.PrintWriter.append(PrintWriter.java:691) at java.io.PrintWriter.append(PrintWriter.java:31) at java.lang.Throwable.printStackTrace(Throwable.java:324) at java.lang.Throwable.printStackTrace(Throwable.java:300) at android.util.Log.getStackTraceString(Log.java:335) at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:59) at com.android.internal.os.RuntimeInit.access$200(RuntimeInit.java:43) at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:85) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
Jahnold.. 5
第二个例子是创建一个永无止境的循环.每次实例化新的MyApplication时,都会运行onCreate方法,并以递归方式创建另一个版本.
将this
在第一个是你的MyApplication的类的实例化的版本,你并不需要创建一个新的.
第二个例子是创建一个永无止境的循环.每次实例化新的MyApplication时,都会运行onCreate方法,并以递归方式创建另一个版本.
将this
在第一个是你的MyApplication的类的实例化的版本,你并不需要创建一个新的.