tomcat下动态编译java类生成class文件

在eclipse下运行成功,tomcat下运行时找不到指定的类解决思路

	public  Class createClassObj(String className){	
		
		StringBuffer sb = new StringBuffer();
		
		sb.append("package com.innovate.middleware.face.neo4j.entity;\r\n");  
		sb.append("import org.neo4j.ogm.annotation.RelationshipEntity;\r\n"); 
		sb.append("@RelationshipEntity(type=\""+className+"\")\r\n"); 
		sb.append("public class "+className+" extends BaseRelationship{}"); 
         
         try {  
             //写入java文件
             String path = BaseRelationship.class.getResource("").getPath();
             String outputPath = path + className + ".java";   
             FileWriter fw = new FileWriter(outputPath);  
             PrintWriter pw = new PrintWriter(fw);  
             pw.println(sb.toString());  
             pw.flush();  
             pw.close();
            //编译
             Class classObj = compilerJavaFile(className,outputPath);
 			return classObj;
   
         } catch (Exception e) {  
             e.printStackTrace();  
         }  finally{  

         }
		return BaseRelationship.class;  
           
     } 
	private Class compilerJavaFile(String className,String outputPath) throws Exception{
        //编译成class文件
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager sjfm = compiler.getStandardFileManager(null, null, null);
		Iterable iter = sjfm.getJavaFileObjects(outputPath);
		
	    String classesPh = Thread.currentThread().getContextClassLoader().getResource("").getPath();

	    
	    String classPath1 = classesPh.replace("classes/", "lib/neo4j-ogm-api-2.1.1.jar");
	    
        //指定编译时依赖的jar包 和class文件所在目录
	    String classPath = classesPh+";"+ classPath1;

		List optionList = new ArrayList(Arrays.asList("-classpath",classPath));
		CompilationTask ct = compiler.getTask(null, sjfm, null, optionList, null, iter);
		ct.call();
		sjfm.close();
		
		 Class clz = Class.forName("com.innovate.middleware.face.neo4j.entity."+className);
		 return clz;
	}

注意 ! ! ! ! !

javac classpath参数表示在指定路径下面寻找所依赖的类。 而寻找类的时候 是根据  包名+类名 进行寻找( com.xxx.类名);

上面代码中 动态创建的子类依赖于同一个路径下的父类, 但是在查找的时候会在当前路径上加上父类的包名,而实际上他们是在同一目录下,所以找不到啦     那么指定classpath的时候就应该指定com之前的路径

你可能感兴趣的:(tomcat下动态编译java类生成class文件)