简体   繁体   English

使用ByteBuddy重新定义java.lang类

[英]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. 我正在尝试使用ByteBuddy重新定义java.lang包(如String.class或Integer.class)上的类,但没有成功。 My question is if that's even possible? 我的问题是,如果可能的话?

This is the code I'm trying in my java agent: 这是我在java代理中尝试的代码:

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: 当我检查日志的输出时,我看到的有关String类的信息是:

[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? 这是否意味着ByteBuddy没有重新定义String类? Is that even possible? 这甚至可能吗?

Many thanks. 非常感谢。

Yes, Byte Buddy can redefine any class but by default, the bootstrap classes are ignored. 是的,Byte Buddy可以重新定义任何类,但默认情况下,引导类会被忽略。 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. 但是我强烈建议你不要搞乱引导类,尤其是String类。 A lot of code makes strong assumptions about the toString class. 很多代码都对toString类做出了很强的假设。

Most JVMs do not allow you to alter the class file format when redefining classes which is why you should enable the .disableClassFormatChanges() option. 重新定义类时,大多数JVM不允许您更改类文件格式,这就是您应该启用.disableClassFormatChanges()选项的原因。 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. 这样做,你不能再添加方法或字段,这是你应该使用Advice类而不是标准拦截器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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