功能:利用java 生成java类 ,并上传至maven私服
使用开源框架:https://github.com/square/javapoet JavaWriter分支
环境:jdk1.8 mavem
import com.squareup.javawriter.JavaWriter;
public class TestClz {
@Test
public void genrateJava() throws IOException {
enumDeclaration();
isOSLinux();
Runtime runtime=Runtime.getRuntime();
try {
Process exec1 = runtime.exec("cmd /k cd D:\\javawriter\\generate && javac TestEnum.java && jar cvf test.jar TestEnum.class &&" +
" mvn deploy:deploy-file -DgroupId=org.testulitmate -DartifactId=code-test -Dversion=0.0.2-SNAPSHOT -Dpackaging=jar -Dfile=D:/javawriter/generate/test.jar -Durl=http://0.0.0.0:8081/nexus/content/repositories/hry-snapshots -DrepositoryId=hry-snapshots");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*生成java类
**/
public static void enumDeclaration() throws IOException {
JavaWriter javaWriter = getReader("TestEnum");
// 生成的包名
javaWriter.emitPackage("com.javawriter.generate");
//定义生成类的信息 类名 类型 访问修饰符 注释
javaWriter.beginType("TestEnum", "enum", EnumSet.of(PUBLIC)).emitJavadoc("this is enum.");
javaWriter.emitEnumValues(Arrays.asList("ZIP","WAR","TAG","Z7"));
javaWriter.endType().close();
}
/**
*构建 javaWriter对象
**/
public static JavaWriter getReader(String className)throws IOException {
String packageName = "com.javawriter.generate";
File outFile = new File("src/main/java/" + packageName.replaceAll("\\.", "/") + "/" + className + ".java");
if(!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
if (!outFile.exists()) {
outFile.createNewFile();
}
System.out.println(outFile.getAbsolutePath());
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outFile));
JavaWriter javaWriter=new JavaWriter(writer);
return javaWriter;
}
/**
*判断是否 是liunx
**/
public static boolean isOSLinux() {
Properties prop = System.getProperties();
String os = prop.getProperty("os.name");
System.out.println(os);
if (os != null && os.toLowerCase().indexOf("linux") > -1) {
return true;
} else {
return false;
}
}
}
网友评论