序列化抽象类的问题

时间:2017-09-11 17:05:24

标签: java android serialization

我试图序列化一个摘要并将其传递给一个活动,但我收到错误java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.example.MainActivity$1)

MainActivity.java

public class MainActivity extends Activity {

    private static final String AUTO_EXTRA = "AUTO_EXTRA";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RelativeLayout l = new RelativeLayout(this);
        l.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        new Setup.auto(this) {
            @Override
            public void onFailure(String message) {

            }
        };
    }
}

Setup.java

public static class Setup {
    public static abstract class auto implements FailedAuto, Serializable {
        public auto(Activity activity) {
            auto a = (auto) this;
            Intent i = new Intent(activity, AutoSetup.class);
            i.putExtra(AUTO_EXTRA, a); // Error happens here.
            activity.startActivity(i);
        }
    }

    private class AutoSetup extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ((auto) getIntent().getSerializableExtra(AUTO_EXTRA)).onFailure("Message");
        }

    }

    private interface FailedAuto {
        void onFailure(String message);
    }
}

我有两个类,MainActivity和Setup,当我运行代码时,我在行i.putExtra(AUTO_EXTRA, a);上得到了错误。我发现Serializing MainActivity解决了这个问题,但我不希望MainActivity成为Serializable而我不明白为什么它认为我是在序列化MainActivity。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

匿名内部类包含包含它的类的引用。在这种情况下,类MainActivity不可序列化。所以你得到了错误。因此,您需要在单独的类文件中创建基类的子类。