import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sun.tools.attach.VirtualMachine;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.NoSuchFieldError;

public class DynamicAttachTest {
    
    // Nested record with type annotation
    public record MyRecord(@MyAnnotation String foo) {}
    
    public static void main(String[] args) throws Exception {
        Class<?> clazz = MyRecord.class;
        clazz.getRecordComponents(); // running this is fine

        VirtualMachine vm = VirtualMachine.attach(String.valueOf(ProcessHandle.current().pid()));
        try {
            vm.loadAgent("agent.jar");
        } finally {
            vm.detach();
        }
        
        // Give agent time to complete retransformation
        Thread.sleep(100);

        // MyRecord is broken, and it's not possible to create new instannces.
        try {
          MyRecord instance = new MyRecord("this causes a NoSuchFieldError");
        } catch (NoSuchFieldError e) {
          // java.lang.NoSuchFieldError: Class DynamicAttachTest$MyRecord does not have member field 'java.lang.String foo'
          e.printStackTrace();
        }
        clazz.getRecordComponents(); // now this segfaults
    }
}

@Target({PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@interface MyAnnotation {
    String value() default "hello";
}
