我试图通过使用一个BaseComponentType
类并在我的ElectricalComponentType
类(和类似的子类)中从中继承来重构代码,如下所示:
public abstract class BaseComponentType {
public static BaseComponentType findByUid ( Class klass, String uid ) {
return new Select().from( klass ).where( "uid = ?", uid ).executeSingle();
}
}
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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句