首页

关于dozer源码包中的JavaCompiler、JavaCompilerFactory编译器及工厂源码分析说明

标签:javaCompiler,编译器工厂,JavaCompilerFactory     发布时间:2018-04-08   

一、前言

关于dozer源码包中的org.drools.commons.jci.compilers.JavaCompiler、org.drools.commons.jci.compilers.JavaCompilerFactory编译器接口及工厂类,其中JavaCompiler定义编译时常用重新方法,具体实现如EclipseJavaCompiler、AbstractJavaCompiler实现类。

二、源码说明

1.JavaCompiler接口

package org.drools.commons.jci.compilers;@b@@b@import org.drools.commons.jci.problems.CompilationProblemHandler;@b@import org.drools.commons.jci.readers.ResourceReader;@b@import org.drools.commons.jci.stores.ResourceStore;@b@@b@public abstract interface JavaCompiler@b@{@b@  public abstract void setCompilationProblemHandler(CompilationProblemHandler paramCompilationProblemHandler);@b@@b@  public abstract JavaCompilerSettings createDefaultSettings();@b@@b@  public abstract CompilationResult compile(String[] paramArrayOfString, ResourceReader paramResourceReader, ResourceStore paramResourceStore);@b@@b@  public abstract CompilationResult compile(String[] paramArrayOfString, ResourceReader paramResourceReader, ResourceStore paramResourceStore, ClassLoader paramClassLoader);@b@@b@  public abstract CompilationResult compile(String[] paramArrayOfString, ResourceReader paramResourceReader, ResourceStore paramResourceStore, ClassLoader paramClassLoader, JavaCompilerSettings paramJavaCompilerSettings);@b@}

2.接口工厂JavaCompilerFactory类

package org.drools.commons.jci.compilers;@b@@b@import java.util.HashMap;@b@import java.util.Map;@b@import org.drools.core.util.ClassUtils;@b@@b@public final class JavaCompilerFactory@b@{@b@@b@  /**@b@   * @deprecated@b@   */@b@  private static final JavaCompilerFactory INSTANCE = new JavaCompilerFactory();@b@  private final Map classCache;@b@@b@  public JavaCompilerFactory()@b@  {@b@    this.classCache = new HashMap(); }@b@@b@  /**@b@   * @deprecated@b@   */@b@  public static JavaCompilerFactory getInstance() {@b@    return INSTANCE;@b@  }@b@@b@  public JavaCompiler createCompiler(String pHint)@b@  {@b@    String className;@b@    if (pHint.indexOf(46) < 0)@b@      className = "org.drools.commons.jci.compilers." + ClassUtils.toJavaCasing(pHint) + "JavaCompiler";@b@    else {@b@      className = pHint;@b@    }@b@@b@    Class clazz = (Class)this.classCache.get(className);@b@@b@    if (clazz == null)@b@      try {@b@        clazz = Class.forName(className);@b@        this.classCache.put(className, clazz);@b@      } catch (ClassNotFoundException e) {@b@        clazz = null;@b@      }@b@@b@@b@    if (clazz == null)@b@      return null;@b@@b@    try@b@    {@b@      return ((JavaCompiler)clazz.newInstance()); } catch (Throwable t) {@b@    }@b@    return null;@b@  }@b@}

3.接口实现类AbstractJavaCompiler、EclipseJavaCompiler

package org.drools.commons.jci.compilers;@b@@b@import org.drools.commons.jci.problems.CompilationProblemHandler;@b@import org.drools.commons.jci.readers.ResourceReader;@b@import org.drools.commons.jci.stores.ResourceStore;@b@@b@public abstract class AbstractJavaCompiler@b@  implements JavaCompiler@b@{@b@  protected CompilationProblemHandler problemHandler;@b@@b@  public void setCompilationProblemHandler(CompilationProblemHandler pHandler)@b@  {@b@    this.problemHandler = pHandler;@b@  }@b@@b@  public CompilationResult compile(String[] pClazzNames, ResourceReader pReader, ResourceStore pStore)@b@  {@b@    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();@b@@b@    if (classLoader == null) {@b@      classLoader = super.getClass().getClassLoader();@b@    }@b@@b@    return compile(pClazzNames, pReader, pStore, classLoader, createDefaultSettings());@b@  }@b@@b@  public CompilationResult compile(String[] pClazzNames, ResourceReader pReader, ResourceStore pStore, ClassLoader pClassLoader) {@b@    return compile(pClazzNames, pReader, pStore, pClassLoader, createDefaultSettings());@b@  }@b@}
package org.drools.commons.jci.compilers;@b@@b@import java.io.ByteArrayOutputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.util.ArrayList;@b@import java.util.Collection;@b@import java.util.Locale;@b@import java.util.Map;@b@import java.util.StringTokenizer;@b@import org.drools.commons.jci.problems.CompilationProblem;@b@import org.drools.commons.jci.problems.CompilationProblemHandler;@b@import org.drools.commons.jci.readers.ResourceReader;@b@import org.drools.commons.jci.stores.ResourceStore;@b@import org.drools.core.util.ClassUtils;@b@import org.eclipse.jdt.core.compiler.IProblem;@b@import org.eclipse.jdt.internal.compiler.ClassFile;@b@import org.eclipse.jdt.internal.compiler.CompilationResult;@b@import org.eclipse.jdt.internal.compiler.Compiler;@b@import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;@b@import org.eclipse.jdt.internal.compiler.ICompilerRequestor;@b@import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;@b@import org.eclipse.jdt.internal.compiler.IProblemFactory;@b@import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;@b@import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;@b@import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;@b@import org.eclipse.jdt.internal.compiler.env.INameEnvironment;@b@import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;@b@import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;@b@@b@public final class EclipseJavaCompiler extends AbstractJavaCompiler@b@{@b@  private final EclipseJavaCompilerSettings defaultSettings;@b@@b@  public EclipseJavaCompiler()@b@  {@b@    this(new EclipseJavaCompilerSettings());@b@  }@b@@b@  public EclipseJavaCompiler(Map pSettings) {@b@    this.defaultSettings = new EclipseJavaCompilerSettings(pSettings);@b@  }@b@@b@  public EclipseJavaCompiler(EclipseJavaCompilerSettings pSettings) {@b@    this.defaultSettings = pSettings;@b@  }@b@@b@  public CompilationResult compile(String[] pSourceFiles, ResourceReader pReader, ResourceStore pStore, ClassLoader pClassLoader, JavaCompilerSettings pSettings)@b@  {@b@    Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings();@b@@b@    Collection problems = new ArrayList();@b@@b@    ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length];@b@    for (int i = 0; i < compilationUnits.length; ++i) {@b@      String sourceFile = pSourceFiles[i];@b@@b@      if (pReader.isAvailable(sourceFile)) {@b@        compilationUnits[i] = new CompilationUnit(this, pReader, sourceFile);@b@      }@b@      else@b@      {@b@        CompilationProblem problem = new CompilationProblem(this, sourceFile)@b@        {@b@          public int getEndColumn() {@b@            return 0;@b@          }@b@@b@          public int getEndLine() {@b@            return 0;@b@          }@b@@b@          public String getFileName() {@b@            return this.val$sourceFile;@b@          }@b@@b@          public String getMessage() {@b@            return "Source " + this.val$sourceFile + " could not be found";@b@          }@b@@b@          public int getStartColumn() {@b@            return 0;@b@          }@b@@b@          public int getStartLine() {@b@            return 0;@b@          }@b@@b@          public boolean isError() {@b@            return true;@b@          }@b@@b@          public String toString() {@b@            return getMessage();@b@          }@b@@b@        };@b@        if (this.problemHandler != null) {@b@          this.problemHandler.handle(problem);@b@        }@b@@b@        problems.add(problem);@b@      }@b@    }@b@@b@    if (problems.size() > 0) {@b@      CompilationProblem[] result = new CompilationProblem[problems.size()];@b@      problems.toArray(result);@b@      return new CompilationResult(result);@b@    }@b@@b@    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();@b@    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());@b@    INameEnvironment nameEnvironment = new INameEnvironment(this, pStore, pClassLoader, pReader)@b@    {@b@      public NameEnvironmentAnswer findType() {@b@        StringBuilder result = new StringBuilder();@b@        for (int i = 0; i < pCompoundTypeName.length; ++i) {@b@          if (i != 0)@b@            result.append('.');@b@@b@          result.append(pCompoundTypeName[i]);@b@        }@b@@b@        return findType(result.toString());@b@      }@b@@b@      public NameEnvironmentAnswer findType(, char[][] pPackageName) {@b@        StringBuilder result = new StringBuilder();@b@        for (int i = 0; i < pPackageName.length; ++i) {@b@          result.append(pPackageName[i]);@b@          result.append('.');@b@        }@b@@b@        result.append(pTypeName);@b@        return findType(result.toString());@b@      }@b@@b@      private NameEnvironmentAnswer findType()@b@      {@b@        if (isPackage(pClazzName)) {@b@          return null;@b@        }@b@@b@        String resourceName = ClassUtils.convertClassToResourcePath(pClazzName);@b@@b@        byte[] clazzBytes = this.val$pStore.read(resourceName);@b@        if (clazzBytes != null) {@b@          char[] fileName = pClazzName.toCharArray();@b@          try {@b@            ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);@b@            return new NameEnvironmentAnswer(classFileReader, null);@b@          } catch (ClassFormatException e) {@b@            throw new RuntimeException("ClassFormatException in loading class '" + fileName + "' with JCI.");@b@          }@b@        }@b@@b@        InputStream is = null;@b@        ByteArrayOutputStream baos = null;@b@        try {@b@          is = this.val$pClassLoader.getResourceAsStream(resourceName);@b@          if (is == null) {@b@            Object localObject1 = null;@b@@b@            return localObject1;@b@          }@b@          byte[] buffer = new byte[8192];@b@          baos = new ByteArrayOutputStream(buffer.length);@b@@b@          while ((count = is.read(buffer, 0, buffer.length)) > 0) {@b@            int count;@b@            baos.write(buffer, 0, count);@b@          }@b@          baos.flush();@b@          char[] fileName = pClazzName.toCharArray();@b@          ClassFileReader classFileReader = new ClassFileReader(baos.toByteArray(), fileName, true);@b@          NameEnvironmentAnswer localNameEnvironmentAnswer = new NameEnvironmentAnswer(classFileReader, null);@b@@b@          return localNameEnvironmentAnswer;@b@        }@b@        catch (IOException e)@b@        {@b@        }@b@        catch (ClassFormatException e)@b@        {@b@        }@b@        finally@b@        {@b@          try@b@          {@b@            if (baos != null)@b@              baos.close();@b@          }@b@          catch (IOException oe) {@b@            throw new RuntimeException("could not close output stream", oe);@b@          }@b@          try@b@          {@b@            if (is != null)@b@              is.close();@b@          }@b@          catch (IOException ie) {@b@            throw new RuntimeException("could not close input stream", ie);@b@          }@b@        }@b@      }@b@@b@      private boolean isPackage()@b@      {@b@        InputStream is = null;@b@        try {@b@          is = this.val$pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName));@b@          if (is != null) {@b@            int i = 0;@b@@b@            return i;@b@          }@b@          String source = pClazzName.replace('.', '/') + ".java";@b@          if (this.val$pReader.isAvailable(source)) {@b@            e = 0;@b@@b@            return e;@b@          }@b@          e = 1;@b@@b@          return e;@b@        }@b@        finally@b@        {@b@          if (is != null)@b@            try {@b@              is.close();@b@            } catch (IOException e) {@b@              throw new RuntimeException("Unable to close stream for resource: " + pClazzName);@b@            }@b@        }@b@      }@b@@b@      public boolean isPackage(, char[] pPackageName)@b@      {@b@        int i;@b@        StringBuilder result = new StringBuilder();@b@        if (parentPackageName != null) {@b@          for (i = 0; i < parentPackageName.length; ++i) {@b@            if (i != 0)@b@              result.append('.');@b@@b@            result.append(parentPackageName[i]);@b@          }@b@@b@        }@b@@b@        if ((parentPackageName != null) && (parentPackageName.length > 0))@b@          result.append('.');@b@@b@        result.append(pPackageName);@b@        return isPackage(result.toString());@b@      }@b@@b@      public void cleanup()@b@      {@b@      }@b@    };@b@    ICompilerRequestor compilerRequestor = new ICompilerRequestor(this, problems, pStore) {@b@      public void acceptResult() {@b@        IProblem[] iproblems;@b@        ClassFile[] clazzFiles;@b@        int i;@b@        if (pResult.hasProblems()) {@b@          iproblems = pResult.getProblems();@b@          for (i = 0; i < iproblems.length; ++i) {@b@            IProblem iproblem = iproblems[i];@b@            CompilationProblem problem = new EclipseCompilationProblem(iproblem);@b@            if (this.this$0.problemHandler != null)@b@              this.this$0.problemHandler.handle(problem);@b@@b@            this.val$problems.add(problem);@b@          }@b@        }@b@        if (!(pResult.hasErrors())) {@b@          clazzFiles = pResult.getClassFiles();@b@          for (i = 0; i < clazzFiles.length; ++i) {@b@            ClassFile clazzFile = clazzFiles[i];@b@            char[][] compoundName = clazzFile.getCompoundName();@b@            StringBuilder clazzName = new StringBuilder();@b@            for (int j = 0; j < compoundName.length; ++j) {@b@              if (j != 0)@b@                clazzName.append('.');@b@@b@              clazzName.append(compoundName[j]);@b@            }@b@            this.val$pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes());@b@          }@b@        }@b@@b@      }@b@@b@    };@b@    Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor, problemFactory, false);@b@@b@    compiler.compile(compilationUnits);@b@@b@    CompilationProblem[] result = new CompilationProblem[problems.size()];@b@    problems.toArray(result);@b@    return new CompilationResult(result);@b@  }@b@@b@  public JavaCompilerSettings createDefaultSettings() {@b@    return this.defaultSettings;@b@  }@b@@b@  final class CompilationUnit@b@    implements ICompilationUnit@b@  {@b@    private final String clazzName;@b@    private final String fileName;@b@    private final char[] typeName;@b@    private final char[][] packageName;@b@    private final ResourceReader reader;@b@@b@    CompilationUnit(, ResourceReader pReader, String pSourceFile)@b@    {@b@      this.reader = pReader;@b@      this.clazzName = ClassUtils.convertResourceToClassName(pSourceFile);@b@      this.fileName = pSourceFile;@b@      int dot = this.clazzName.lastIndexOf(46);@b@      if (dot > 0)@b@        this.typeName = this.clazzName.substring(dot + 1).toCharArray();@b@      else {@b@        this.typeName = this.clazzName.toCharArray();@b@      }@b@@b@      StringTokenizer izer = new StringTokenizer(this.clazzName, ".");@b@      this.packageName = new char[izer.countTokens() - 1][];@b@      for (int i = 0; i < this.packageName.length; ++i)@b@        this.packageName[i] = izer.nextToken().toCharArray();@b@    }@b@@b@    public char[] getFileName()@b@    {@b@      return this.fileName.toCharArray();@b@    }@b@@b@    public char[] getContents() {@b@      byte[] content = this.reader.getBytes(this.fileName);@b@@b@      if (content == null) {@b@        return null;@b@      }@b@@b@      return new String(content).toCharArray();@b@    }@b@@b@    public char[] getMainTypeName() {@b@      return this.typeName;@b@    }@b@@b@    public char[][] getPackageName() {@b@      return this.packageName;@b@    }@b@  }@b@}




  • ◆ 相关内容