gpt4 book ai didi

Java:在子类中使用父类的静态方法

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:26:33 28 4
gpt4 key购买 nike

我正在尝试通过使用 BaseComponentType 类并在我的 ElectricalComponentType 类中继承它来重构我的代码(和类似的子类),如下:

基础组件类型.java

public abstract class BaseComponentType {

public static BaseComponentType findByUid ( Class klass, String uid ) {

return new Select().from( klass ).where( "uid = ?", uid ).executeSingle();

}

}

ElectricalComponentType.java

public class ElectricalComponentType extends BaseComponentType {

public static ElectricalComponentType findByUid( String uid ) {

return (ElectricalComponentType) findByUid( ElectricalComponentType.class, uid );

}

}

我需要做的是调用 ElectricalComponentType.findByUid( 'a1234' ) 但如果我不必在 中定义 findByUid 就好了ElectricalComponentType 类,而是可以从 BaseComponentType 继承此功能。

您会注意到有两件事阻碍了您:

  1. 我需要 findByUid 父方法中的 ElectricalComponentType 类。

  2. 我需要返回 ElectricalComponentType 对象(或任何子类对象)而不是 BaseComponentType 类对象。

有办法吗?

最佳答案

使用泛型并且只有父类方法:

public abstract class BaseComponentType {
public static <T extends BaseComponentType> T findByUid(Class<T> klass, String uid) {
return new Select().from( klass ).where( "uid = ?", uid ).executeSingle();
}
}

关于Java:在子类中使用父类的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23447403/

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