Java中的静态通用字段 [英] Static generic field in Java

查看:45
本文介绍了Java中的静态通用字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将通过传递通用字段(演示者)来实现片段的初始化,然后将该演示者连接到创建的View.

I going to implement initialization of fragment with passing my generic field (presenter) and then connect this presenter to created View.

public class BaseViewFragment <P extends BasePresenter> extends Fragment implements BaseView {

static private P presenter; //the problme is here, I do not allowed this
static private BaseViewFragment baseViewFragment;
.
.
.

public static <P extends BasePresenter> BaseViewFragment initialize(P presenter) {

    if (baseViewFragment != null) {
        presenter.setView(baseViewFragment);
    } else {

        baseViewFragment = new BaseViewFragment();
        presenter.setView(baseViewFragment);
    }

    BaseViewFragment.presenter= presenter;
    return baseViewFragment;
}

但是似乎不允许使用通用静态字段.我该如何处理?

But it seems that generic static field is not allowed. How I can handle this?

推荐答案

来自 Java文档:

不能声明类型为类型参数的静态字段

Cannot Declare Static Fields Whose Types are Type Parameters

一个类的静态字段是由所有人共享的一个类级别的变量类的非静态对象.因此,静态类型为参数是不允许的.

A class's static field is a class-level variable shared by all non-static objects of the class. Hence, static fields of type parameters are not allowed.

这是不可能的,因为 BaseViewFragment 类的所有实例都共享一个静态字段,并且如果允许,则可以为每个新的 BaseViewFragment 实例指定一个新字段 Generic Type参数.因此,这是不允许的.

It is not possible because a static field is shared by all the instances of the class BaseViewFragment, and if allowed, for every new BaseViewFragment instance you can specify a new Generic Type parameter. So it is not allowed.

您可以做的是:使用 setPresenter 方法将Presenter实例传递给Fragment并进行初始化.

What you can do is: pass the Presenter instance to the Fragment using a setPresenter method and initialize.

例如,

    P presenter; // no need for static

    public BaseViewFragment() {

    }

    public void setPresenter(P presenter) {
       this.presenter = presenter;
    }

设置演示者:

baseViewFragment  = new BaseViewFragment(); 
baseViewFragment.setPresenter(presenter);

顺便说一句,在静态变量中包含 Fragment 可能会导致内存泄漏( Activity ).您是否在 Fragment 销毁时清除该字段?如果不是这样,您将泄漏您的 Fragment 和绑定的 Activity 和其中的所有 Views .

By the way, having a Fragment in a static variable might lead to memory (Activity) leaks. Are you clearing that field when the Fragment destroys? If not you are leaking your Fragment and the bound Activity and all the Views in it.

这篇关于Java中的静态通用字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆