我正在尝试创建一个扩展通用抽象类(MappingObject.class)的类(MoMoTest.class)。一切看起来都不错,除了 JCodeModel 没有导入缩小的类(MoTest.class),尽管我用 codeModel.ref 创建了它的 JClass:
映射对象类:
package test;
public abstract class MappingObject<T> {
protected T dataObject;
public MappingObject( T dataObject ) {
this.dataObject = dataObject;
}
public abstract T getDataObject();
public abstract String getStandardFormat();
}
MoTest.class:
package test;
public class MoTest {
}
MappingObjectCreator.class:
package test;
import com.sun.codemodel.*;
import java.io.File;
import java.io.IOException;
public class MappingObjectCreator {
public JDefinedClass getMappingObject(JCodeModel codeModel, JPackage jPackage, Class<?> clazz) throws JClassAlreadyExistsException {
JClass ref = codeModel.ref(clazz); // Not imported in MoMoTest.class
JDefinedClass definedClass = jPackage._class("Mo" + ref.name());
JClass superClass = codeModel.ref(MappingObject.class).narrow(ref);
definedClass._extends(superClass);
JFieldRef dataObject = JExpr.ref("dataObject");
JMethod constructor = definedClass.constructor(JMod.PUBLIC);
JVar param = constructor.param(ref, ref.name());
constructor.body().invoke("super").arg(param);
JMethod getDataObject = definedClass.method(JMod.PUBLIC, ref, "getDataObject");
getDataObject.annotate(codeModel.ref(Override.class));
getDataObject.body()._return(dataObject);
JMethod getStandardFormat = definedClass.method(JMod.PUBLIC, String.class, "getStandardFormat");
getStandardFormat.annotate(codeModel.ref(Override.class));
getStandardFormat.body()._return(dataObject.invoke("toString"));
return definedClass;
}
public void getMappingObject(Class clazz, String path) throws JClassAlreadyExistsException, IOException {
JCodeModel codeModel = new JCodeModel();
JPackage jPackage = codeModel._package(clazz.getPackage().getName());
getMappingObject(codeModel, jPackage, clazz);
codeModel.build(new File(path));
}
public static void main(String[] args) throws IOException, JClassAlreadyExistsException {
new MappingObjectCreator().getMappingObject(MoTest.class, "src/main/java");
}
}
结果(MoMoTest.class):
package test;
public class MoMoTest
extends MappingObject<test.MoTest>
{
public MoMoTest(test.MoTest MoTest) {
super(MoTest);
}
@Override
public test.MoTest getDataObject() {
return dataObject;
}
@Override
public String getStandardFormat() {
return dataObject.toString();
}
}
那么为什么 Motest.class 没有导入 MomoTest.class 呢?