检测java核心类

检测java核心类,java,instrumentation,Java,Instrumentation,出于某种检测目的,我需要在java.lang.string中添加一个变量。有可能吗?当我这样做时,我会得到以下异常: java.lang.UnsupportedOperationException: class redefinition failed: attempted to change the schema (add/remove fields) at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method

出于某种检测目的,我需要在java.lang.string中添加一个变量。有可能吗?当我这样做时,我会得到以下异常:

java.lang.UnsupportedOperationException: class redefinition failed: attempted to change the schema (add/remove fields)
    at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method)
    at sun.instrument.InstrumentationImpl.redefineClasses(InstrumentationImpl.java:170)
    at com.javapapers.java.instrumentation.DurationAgent.premain(DurationAgent.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
    at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)

事实上,异常已经包含了所有相关信息。异常的类型名
java.lang.UnsupportedOperationException
包含术语“unsupport operation”,其消息不会命名不受支持的操作:“试图更改架构(添加/删除字段)”

换句话说,HotSpot JVM不支持在类重新定义期间添加或删除字段,无论是在核心类还是任何其他类上尝试。如各国所述:

重新定义可能会更改方法体、常量池和属性。重新定义不得添加、删除或重命名字段或方法、更改方法的签名或更改继承。这些限制可能会在未来的版本中取消

对于其他类,加载时检测可能会有所帮助,在运行时第一次定义之前更改声明的字段,但是对于像
java.lang.String
这样的关键类,即使在加载代理之前也必须存在,这不是一个选项


更改
字符串
类的唯一可能方法是在JVM启动时为引导类路径预先添加一个替代实现,但是,我强烈建议不要以这种方式更改配置。在使用这样一个基本类时,您很容易破坏整个JVM,甚至一个JVM(版本)发生的情况可能会破坏另一个JVM(或下一个版本).

@M0ns1f不要将堆栈跟踪格式化为块引号,而是使用代码格式化。@JimGarrison okey,下次会怎样