gpt4 book ai didi

java - 如何在将属性传递给父类(super class)构造函数之前修改属性?

转载 作者:搜寻专家 更新时间:2023-11-01 02:35:24 25 4
gpt4 key购买 nike

一般问题:

给定一个这样的类:

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);
}
}

有没有办法在调用super()方法之前修改initialValue

这是我的具体用例:

我正在编写一个小型包装器 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 View 期望属性(在 layout.xml 文件中)使用 snake case。例如:

  • use_artwork
  • default_artwork
  • hide_on_touch
  • 等等

然而,原生 View 的绝大多数默认属性使用驼峰式大小写:

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

因此,为了保持一致性,我想用相同的驼峰式属性替换 ExoPlayer 属性:

  • useArtwork
  • defaultArtwork
  • 隐藏OnTouch
  • 等等

但是因为 super() 必须在构造函数中的任何其他代码之前调用,所以我没有机会在父类(super class)初始化之前修改 AttributeSet:

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

这有什么技巧吗?还是根本不可能?

最佳答案

理想情况下,您会执行以下操作:

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

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

注意:该方法必须是静态的!您不能在对 Sub 中的 super 构造函数的调用中使用非静态方法。正如任何非静态方法可能期望它对完全初始化 对象进行操作一样。你没有,当你之前调用方法时,“this”和“super”构造函数被调用并且可以完成它们的初始化工作!

另一种选择是使 Sub 构造函数成为私有(private),并有一个静态工厂方法来处理传入的字符串,然后立即调用 new Sub()与按摩输入。

关于java - 如何在将属性传递给父类(super class)构造函数之前修改属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com