スーパークラスのコンストラクタに渡す前に属性を変更するには?

stevendesu:

一般的な質問:

そのようなクラスを考えます:

public class Super {
    private String value;
    public Super(String initialValue)
    {
        this.value = initialValue;
    }
    public String getValue()
    {
        return value;
    }
}

そしてそうのようなサブクラス:

public class Sub extends Super {
    public Sub(String initialValue)
    {
        super(initialValue);
    }
}

修正する方法はありinitialValue呼び出す前に、super()方法は?

ここに私の具体的なユースケースです。

そのように私は、小さなラッパーExoPlayerを書いています:

public class BFPlayer extends PlayerView {
    private SimpleExoPlayer player;

    public BFPlayer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        TypedArray attributes = context.obtainStyledAttributes(attrs,
                R.styleable.BFPlayer);

        player = ExoPlayerFactory.newSimpleInstance(context);

        this.setPlayer(player);

        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context,
                Util.getUserAgent(context, "TODO: USER AGENT STRING"));

        MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
                .createMediaSource(Uri.parse(attributes.getString(R.styleable.BFPlayer_videoSrc)));

        player.prepare(videoSource);

        player.setPlayWhenReady(true);
    }
}

ExoPlayerのPlayerViewビューは、(内の属性見込んlayout.xmlファイル)はヘビのケースを使用します。例えば:

  • use_artwork
  • default_artwork
  • hide_on_touch

しかし、大多数のネイティブビューのデフォルトの属性のは、キャメルケースを使用します。

  • addStatesWithChildren
  • alwaysDrawnWithCache
  • animateLayoutChanges
  • animateCache
  • clipChildren
  • clipToPadding

したがって、一貫性のために私はExoPlayerが同一のキャメルケースの属性と属性を交換したいと思います:

  • useArtwork
  • defaultArtwork
  • hideOnTouch

しかしのでsuper()、コンストラクタ内の他のコードの前に呼び出される必要があり、私はスーパークラスの初期化の前に属性セットを修正する機会を持っていません。

    public BFPlayer(Context context, AttributeSet attrs, int defStyle) {
        AttributeSet modifiedAttrs = camelToSnake(attrs);
        super(context, modifiedAttrs, defStyle);
        init(context, attrs, defStyle);
    }

これにトリックはありますか?それとも、単に不可能ですか?

GhostCat敬礼モニカC.:

理想的には、あなたのような何かをするだろう。

class Sub extends Super {
  private static String massageArgument(String incoming) { 
    return incoming.replaceAll("foo", "bar"); 
  }

  public Sub(String incoming) {
    super(massageArgument(incoming));
  }

ノート:このメソッドは静的である必要があります!あなたはサブでスーパーコンストラクタにそのコール内の非静的メソッドを使用することはできません。任意の非静的メソッドは、それが上で動作することを期待するかもしれませんが完全に初期化オブジェクト。あなたはどちらがありません、あなたがメソッド呼び出したときに前に「この」と「スーパー」コンストラクタが呼び出され、それらの初期化作業を行うことができます!

他のオプションは、サブコンストラクタを作ることであろうプライベート操作していること、着信文字列を、静的なファクトリメソッドを持って、その後、呼び出し、new Sub()マッサージ入力してすぐ。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=187595&siteId=1
おすすめ