加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:19:53 所属栏目:Java 来源:网络整理
导读:我试图通过使用BaseComponentType类并在我的ElectricalComponentType类(和类似的子类)中继承我的代码来重构我的代码,如下所示: BaseComponentType.java public abstract class BaseComponentType { public static BaseComponentType findByUid ( Class klas
我试图通过使用BaseComponentType类并在我的ElectricalComponentType类(和类似的子类)中继承我的代码来重构我的代码,如下所示:

BaseComponentType.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’),但如果我不必在ElectricalComponentType类中定义findByUid而是从BaseComponentType继承此功能,那将会很棒.

你会发现有两件事情在路上:

>我需要findByUid父方法中的ElectricalComponentType类.
>我需要返回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();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读