我使用 bytebuddy-agent 为 Jedis 类添加一个动态字段,在 JedisCluster 构造函数中,将创建三个 Jedis 实例,这将导致 JVM 加载 Jedis 类。让我困惑的是
当我将代码 Jedis jedis = new Jedis("localhost", 6379)
放在代码 JedisCluster cluster = new JedisCluster(nodes)
前面时,bytebuddy-agent 将动态字段添加到Jedis 类成功如下。
@Test
public void testOnConstruct() throws Exception {
Jedis jedis = new Jedis("localhost", 6379);
Set<HostAndPort> nodes = new HashSet<>(3);
nodes.add(new HostAndPort("192.168.146.128", 7001));
nodes.add(new HostAndPort("192.168.146.128", 7002));
nodes.add(new HostAndPort("192.168.146.128", 7003));
JedisCluster cluster = new JedisCluster(nodes);
}
如果我把 Jedis jedis = new Jedis("localhost", 6379)
放在 JedisCluster cluster = new JedisCluster(nodes)
之后,bytebuddy-agent 不能添加动态成功进入 Jedis 类(class)。
我需要你的帮助,谢谢。
最佳答案
不可能向已加载的类添加字段,JVM 禁止这样做。为此,您需要在第一次加载之前添加该字段。
关于java - 可以为加载类定义新字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47017235/