Maven archetype + Velocity:如何显示当前目录并删除某个目录

问题描述

因为我想使用原型来创建一个多合一的项目,并通过requiredProperty删除一些文件和包, 我可以使用 VeLocity 通过 #if 显示一些代码,如下所示:

#if(${MysqL})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else

文件或目录无法删除

我使用代码调用 JDK 方法获取当前日期:

#set( $ldt = $package.getClass().forName("java.time.LocalDateTime").getmethod("Now").invoke(null) )
#set( $dtf = $package.getClass().forName("java.time.format.DateTimeFormatter").getmethod("ofPattern",$package.getClass()).invoke(null,"yyyy/MM/dd HH:mm:ss") )
#set( $date = $ldt.format($dtf))

所以我认为可能可以调用文件 API 来获取当前目录并将其删除

#set( $CurPath = $package.getClass().forName("java.nio.file.Paths").getmethod("get").invoke(".") )
#set( $CurPathStr = $CurPath.toAbsolutePath().normalize().toString() )
#set( $CurPathStrSys = $package.getClass().forName("java.lang.System").getmethod("getProperty").invoke("user.dir") )

但得到错误

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.2.0:generate (default-cli) on project standalone-pom: Error merging veLocity templates: Invocation of method 'getmethod' in  class java.lang.class threw exception java.lang.NoSuchMethodException: java.nio.file.Paths.get() at archetype-resources/__rootArtifactId__-service/src/main/java/MainApplication.java[line 5,column 69] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors,re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions,please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

解决方法

错误是java反射错误,我得到了这样的乐趣:

#set( $RunPath = $package.getClass().forName("java.lang.System").getMethod("getProperty",$package.getClass().forName("java.lang.String")).invoke(null,"user.dir") )
#set( $separator = $package.getClass().forName("java.io.File").getField("separator").get($package.getClass().forName("java.lang.String")))
#set( $packagePath = $package.replace(".",$separator))
#set( $CurPath = $RunPath + $separator + $parentArtifactId + $separator + $artifactId + $separator + "src" + $separator + "main" + $separator + "java" + $separator +  $packagePath + $separator  )

所以它可以通过这个删除一些文件:

#if(${mongo} == "false")
    #set($mongoConfig = $CurPath + "dao" + $separator + "config" + $separator  +  "MongoConfig.java")
    #set($isDelete = $package.getClass().forName("java.io.File").getMethod("delete").invoke($package.getClass().forName("java.io.File").getConstructor($package.getClass().forName("java.lang.String")).newInstance($mongoConfig)))
#end