How to generate strings that share the same hashcode in Java?

前端 未结 6 1287
余生分开走
余生分开走 2020-12-28 10:09

An existing system written in Java uses the hashcode of a string as its routing strategy for load balancing.

Now, I cannot modify the system but ne

6条回答
  •  再見小時候
    2020-12-28 10:30

    You can instrument the java.lang.String class so its method hashCode() will always return the same number.

    I suppose Javassist is the easiest way to do such an instrumentation.

    In short:

    • obtain an instance of java.lang.instrument.Instrumentation by using a Java-agent (see package java.lang.instrument documentation for details)
    • redefine java.lang.String class by using Instrumentation.redefineClasses(ClassDefinition[]) method

    The code will look like (roughly):

    ClassPool classPool = new ClassPool(true);
    CtClass stringClass = classPool.get("java.lang.String");
    CtMethod hashCodeMethod = stringClass.getDeclaredMethod("hashCode", null);
    hashCodeMethod.setBody("{return 0;}");
    byte[] bytes = stringClass.toBytecode();
    ClassDefinition[] classDefinitions = new ClassDefinition[] {new ClassDefinition(String.class, bytes);
    instrumentation.redefineClasses(classDefinitions);// this instrumentation can be obtained via Java-agent
    

    Also don't forget that agent manifest file must specify Can-Redefine-Classes: true to be able to use redefineClasses(ClassDefinition[]) method.

提交回复
热议问题