LatencyFighter
LatencyFighter

Reputation: 351

How to load a Java class from the classpath *as a byte array* for bytecode injection?

There is a class com.mycompany.MyBadClass in my Java classpath.

I'm trying to instrument the JVM with a javaagent to swap MyBadClass for MyGoodClass, which is also in the classpath.

public static class BugFixAgent {
  public static void premain(String args, Instrumentation inst) {
    inst.addClassFileTransformer(new ClassFileTransformer() {
      @Override
      public byte[] transform(ClassLoader loader, 
                              String className, 
                              Class<?> classBeingRedefined, 
                              ProtectionDomain protectionDomain, 
                              byte[] classfileBuffer) {
        if (className.equals("com/mycompany/MyBadClass")) {
          return patchedClassAsByteArray; // <====== ??????
        } else {
          return null; // skips instrumentation for other classes
        }
      }
    });
  }
}

So my question is: How do I load a byte array of com.mycompany.MyGoodClass from the classpath programmatically?

Upvotes: 0

Views: 376

Answers (2)

henry
henry

Reputation: 6096

You can get an InputStream with

loader.getResourceAsStream(name + ".class");

Which can then be converted to a byte array.

Upvotes: 2

GhostCat
GhostCat

Reputation: 140427

You basically want to

  • first scan your classpath ( see here for ideas )
  • you basically stop when you "found" MyGoodClass - and ideally the result of the scan process is some sort of handle that allows you to access the file belonging to the class

If your class path just contains directory names, that is pretty easy - but maybe your class sits in some JAR, and then some more work is required.

But as said: the core thing is the initial "scan". That is a (somewhat) solved problem, it only requires "work" to get done.

Upvotes: 0

Related Questions