简体   繁体   中英

Redefine java.lang classes with ByteBuddy

I'm trying to redefine classes on the java.lang package such as String.class or Integer.class using ByteBuddy but with no success. My question is if that's even possible?

This is the code I'm trying in my java agent:

public static void premain(String agentArgs, Instrumentation inst) {
    new AgentBuilder.Default()
            .type(named("java.lang.String"))
            .transform((builder, typeDescription, classLoader) ->
                    builder.method(named("toString"))
                            .intercept(FixedValue.value("toString() got hacked!")))
            .with(AgentBuilder.Listener.StreamWriting.toSystemOut())
            .with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
            .with(AgentBuilder.TypeStrategy.Default.REDEFINE)
            .installOn(inst);
}

When I check the output of the logs and what I see regarding the String class is:

[Byte Buddy] IGNORE [[Ljava.lang.String; [null, null]
[Byte Buddy] COMPLETE [[Ljava.lang.String; [null, null]

Does this means that ByteBuddy is not redefining the String class? Is that even possible?

Many thanks.

Yes, Byte Buddy can redefine any class but by default, the bootstrap classes are ignored. You can override this default setting by defining a custom ignore matcher or just removing it alltogether:

AgentBuilder agentBuilder = new AgentBuilder.Default().ignore(none());

I would however strongly advice you against messing with the bootstrap classes and especially with the String class. A lot of code makes strong assumptions about the toString class.

Most JVMs do not allow you to alter the class file format when redefining classes which is why you should enable the .disableClassFormatChanges() option. Doing so, you cannot longer add methods or fields which is when you should look into using the Advice class instead of the standard interceptors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM