在java代码里需要再添加一个注解,就是一行代码,让客户手动修改肯定不合适,所以还是要用程序修正下
IFile file = EIPBaseUtils.getResourceFromProject(fullPathName, projectName);
ICompilationUnit parentCU = JavaCore.createCompilationUnitFrom(file);
this.parentCU = compilationUnit;
IType[] types = compilationUnit.getAllTypes();
if(types!= null && types.length>0){
IType t = types[0];//直接取第一个
for(IField f : t.getFields()){
String Annotation = "xxxxx";
fixCode(f,Annotation,index);//给字段加上注解
}
private void fixCode ( IField f, String newFieldString,int index) throws Exception{
ICompilationUnit copy = parentCU.getWorkingCopy(null); //获取副本
IBuffer buffer = copy.getBuffer();
buffer.replace(f.getSourceRange().getOffset()+index, 0, newFieldString);//第二个参数给0就是插入,大于0的话就是替换
copy.reconcile(0, false, copy.getOwner(), null);
copy.createImport("com.XX", null, null);//还要把依赖的包导入,不然改了也报错
copy.reconcile(0, false, copy.getOwner(), null);
copy.commit(false, null); //如果commit报错,就在修改前刷新下文件,
copy.discardWorkingCopy();//删除副本
}
上述的代码,针对每一个字段编译单元都修改后提交一次,应该可以改进成遍历完所有field再提交,那copy也就不能再fixCode里获取了,回去再试试