Question_283
Question_283

Reputation: 21

Java Agent "java.lang.UnsupportedOperationException: class redefinition failed: attempted to change method modifiers"

I am trying to change the method access modifier through an agent via javassist, however, I get an error. So, is it possible to change the access modifier via java agent and how to fix it? Is there any other way to influence the bytecode in runtime?

Agent

public static void premain(String args, Instrumentation instrumentation)
    throws ClassNotFoundException, IOException, UnmodifiableClassException, NotFoundException {

  final ClassPool pool = ClassPool.getDefault();
  pool.appendClassPath(new LoaderClassPath(Thread.currentThread().getContextClassLoader()));

  final ClassFile file = pool.get("...")
      .getClassFile();
  file.getMethod("...").setAccessFlags(AccessFlag.PUBLIC);

  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  DataOutputStream dos = new DataOutputStream(bytes);
  file.write(dos);
  
  Class<?> clazz = ...;

  instrumentation.redefineClasses(new ClassDefinition(clazz, bytes.toByteArray()));
}

MANIFEST

Manifest-Version: 1.0
Premain-Class: ...Agent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
Can-Set-Native-Method-Prefix: true

Upvotes: 0

Views: 1670

Answers (0)

Related Questions