【问题标题】:Can I shorten casts?我可以缩短演员表吗?
【发布时间】:2012-06-03 12:45:56
【问题描述】:

是否可以创建一个函数来缩短强制转换,例如(伪代码):

MyFragment fragment = (MyFragment) getFragmentManager().findFragmentByTag("mytag");
//shorten:
findByTag(MyFragment.class, "mytag");


private Fragment findByTag(Class<?> cast, String tag) {
    return (cast) getFragmentManager().findFragmentByTag(tag);
}

【问题讨论】:

    标签: java android android-fragments


    【解决方案1】:

    将您的代码修复如下:

    private <F extends Fragment> F findByTag(Class<F> cast, String tag) {
        return (F) getFragmentManager().findFragmentByTag(tag);
    }
    

    现在您可以在不强制转换的情况下调用它:

    MyFragment f1 = findByTag(MyFragment.class, "aaaaa");
    YourFragment f2 = findByTag(YourFragment.class, "bbbbb");
    

    【讨论】:

    • 这会给你一个警告,并可能导致ClassCastException 在其他地方。使用cast.cast(getFragmentManager().findFragmentByTag(tag)) 更好,因为它会在出现问题时立即抛出。
    猜你喜欢
    • 2011-04-04
    • 2021-10-31
    • 2011-07-22
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2012-10-30
    相关资源
    最近更新 更多