In the classfile API introduced by Java 24, there are several versions of the transformClass methods. In particular if the name of the
transformed class is unchanged compared to the original class, then it is recommended to use the simplest version of the method that takes only 2
arguments. This makes the code shorter, clearer, and reduces chances for mistakes.
Remove the class name argument of the transformClass call.
public static void transformClassFile(Path path) throws IOException {
ClassFile classFile = ClassFile.of();
ClassModel classModel = classFile.parse(path);
byte[] newBytes = classFile.transformClass(classModel,
classModel.thisClass().asSymbol(), // Noncompliant
(classBuilder, classElement) -> {
if (!(classElement instanceof MethodModel methodModel &&
methodModel.methodName().stringValue().startsWith("debug"))) {
classBuilder.with(classElement);
}
});
}
public static void transformClassFile(Path path) throws IOException {
ClassFile classFile = ClassFile.of();
ClassModel classModel = classFile.parse(path);
byte[] newBytes = classFile.transformClass(classModel,
(classBuilder, classElement) -> {
if (!(classElement instanceof MethodModel methodModel &&
methodModel.methodName().stringValue().startsWith("debug"))) {
classBuilder.with(classElement);
}
});
}