上述的问题统统可以交由maven shade plugin中relocate标签完成。
首先,我们来看如何修改包名。
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<relocation>
<pattern>org.codehaus.plexus.util</pattern>
<shadedPattern>org.shaded.plexus.util</shadedPattern>
<excludes>
<!-- 将pattern对应的package进行改名操作,但是对以下两个exclude标签所对应的package并不会进行改名操作。 -->
<exclude>org.codehaus.plexus.util.xml.Xpp3Dom</exclude>
<exclude>org.codehaus.plexus.util.xml.pull.*</exclude>
</excludes>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
然后,我们再看看如何修改类名。以下代码将KafkaService类名改为KafkaObject。
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<relocation>
<pattern>org.codehaus.plexus.util.KafkaService</pattern>
<shadedPattern>org.shaded.plexus.util.KafkaObject</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
最后,我们再来看看如何将class字节码文件中字符串A更改为字符串B(注意大小写敏感)。
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<relocation>
<pattern>A</pattern>
<shadedPattern>B</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
上面的配置能够将class字节码文件中的字符串A转为B。但是上述配置可能会存在着误杀的问题。比如说,对于字符串AC将于转为BC。这个显然不是我们所想要的。所以这个时候我们需要对上述的配置进行相应的修改。
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<relocation>
<pattern>^A$</pattern>
<shadedPattern>B</shadedPattern>
<rawString>true</rawString>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
这个^A$中^、$表示以字符串A开头,并以字符串A结尾。就可以完成字符串到字符串B的精准转换了。