我试图通过使用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' )
,但是如果我不必在findByUid
类中定义ElectricalComponentType
,而是可以从BaseComponentType
继承此功能,那就太好了。您会注意到有两件事妨碍您:
ElectricalComponentType
父方法中的findByUid
类。 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();
}
}