Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Records (Java 17) can't get enhanced with CtNewMethod#make #494

Open
Novanic opened this issue Oct 28, 2024 · 0 comments
Open

Records (Java 17) can't get enhanced with CtNewMethod#make #494

Novanic opened this issue Oct 28, 2024 · 0 comments

Comments

@Novanic
Copy link

Novanic commented Oct 28, 2024

I have tried to add a new method to an record (Java 17), but javassist corrupts the class signature when CtNewMethod#make(CtClass, String, CtClass[], CtClass[], String, CtClass) is used.

The class signature / header in this example will get changed from "public record JavasisstTestClass(String testValue)" to "public record JavasisstTestClass(testValue Ljavassist/test/JavasisstTestClass;)", which is broken.

Record to enhance:

package javassist.test;

public record JavasisstTestClass(String testValue) {

}

Reproducer:

package javassist.test;

import javassist.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavassistTest {

	public static void main(String[] args) throws Exception {
		ClassPool cp = new ClassPool(true);

		CtClass ctClass = cp.get("javassist.test.JavasisstTestClass");

		// doesn't work, the class signature gets corrupted
		// The class signature will be 'public record JavasisstTestClass(testValue Ljavassist/test/JavasisstTestClass;)'
		// instead of 'public record JavasisstTestClass(String testValue)'.
		CtMethod newMethod = CtNewMethod.make(CtClass.booleanType, "isTest", null, null, "{ return false; }", ctClass);
		ctClass.addMethod(newMethod);

		dump(ctClass);
	}

	private static void dump(CtClass ctClass) throws IOException, CannotCompileException, NotFoundException {
		byte[] bytecode = ctClass.toBytecode();
		dump(ctClass.getName(), bytecode);
	}

	private static void dump(String className, byte[] classBytes) throws IOException {
		Path path = Paths.get("C:/Temp/bytecode/javassist");
		Path file = path.resolve(className.replace('.', '/') + ".class");

		Files.createDirectories(file.getParent());
		Files.write(file, classBytes, new OpenOption[0]);
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant