1 package spoon.support; 2 3 import java.io.File ; 4 import java.util.ArrayList ; 5 import java.util.List ; 6 7 import org.eclipse.jdt.internal.compiler.ClassFile; 8 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; 9 import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; 10 11 import spoon.processing.AbstractProcessor; 12 import spoon.processing.FileGenerator; 13 import spoon.reflect.declaration.CtSimpleType; 14 import spoon.support.util.JDTCompiler; 15 16 19 public class ByteCodeOutputProcessor extends AbstractProcessor<CtSimpleType<?>> 20 implements FileGenerator<CtSimpleType<?>> { 21 22 25 public static final String CLASS_EXT = ".class"; 26 27 private File outputDir; 28 29 private List <ICompilationUnit> units = new ArrayList <ICompilationUnit>(); 30 31 private List <File > printed = new ArrayList <File >(); 32 33 private JavaOutputProcessor javaPrinter; 34 35 41 public ByteCodeOutputProcessor(JavaOutputProcessor javaPrinter, 42 File outputDirectory) { 43 this.outputDir = outputDirectory; 44 this.javaPrinter = javaPrinter; 45 } 46 47 public List <File > getCreatedFiles() { 48 return printed; 49 } 50 51 public File getOutputDirectory() { 52 return outputDir; 53 } 54 55 58 public long getJavaCompliance() { 59 switch (getFactory().getEnvironment().getComplianceLevel()) { 60 case 1: 61 return ClassFileConstants.JDK1_1; 62 case 2: 63 return ClassFileConstants.JDK1_2; 64 case 3: 65 return ClassFileConstants.JDK1_3; 66 case 4: 67 return ClassFileConstants.JDK1_4; 68 case 5: 69 return ClassFileConstants.JDK1_5; 70 case 6: 71 return ClassFileConstants.JDK1_6; 72 } 73 return ClassFileConstants.JDK1_5; 74 } 75 76 public void process(CtSimpleType<?> element) { 77 if (!element.isTopLevel()) 78 return; 79 javaPrinter.getCreatedFiles().clear(); 81 javaPrinter.createJavaFile(element); 82 83 for (File f : javaPrinter.getCreatedFiles()) { 84 try { 85 units.add(JDTCompiler.getUnit(element.getQualifiedName(), f)); 86 } catch (Exception e) { 87 e.printStackTrace(); 88 } 89 } 90 91 } 92 93 @Override 94 public void processingDone() { 95 try { 96 JDTCompiler compiler = new JDTCompiler(); 98 compiler.getCompilerOption().sourceLevel = getJavaCompliance(); 99 compiler.compile(units.toArray(new ICompilationUnit[0])); 100 101 getOutputDirectory().mkdirs(); 102 103 for (ClassFile f : compiler.getClassFiles()) { 104 105 ClassFile.writeToDisk(true, getOutputDirectory() 106 .getAbsolutePath(), new String (f.fileName()).replace( 107 '/', File.separatorChar) 108 + CLASS_EXT, f); 109 } 110 } catch (Exception e) { 111 e.printStackTrace(); 112 } 113 114 } 115 116 public void setOutputDirectory(File directory) { 117 this.outputDir = directory; 118 } 119 120 } 121 | Popular Tags |