How to read the value of a private field from a different class in Java?

前端 未结 14 1721
梦毁少年i
梦毁少年i 2020-11-21 11:28

I have a poorly designed class in a 3rd-party JAR and I need to access one of its private fields. For example, why should I need to choose priv

14条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 12:00

    Reflection isn't the only way to resolve your issue (which is to access the private functionality/behaviour of a class/component)

    An alternative solution is to extract the class from the .jar, decompile it using (say) Jode or Jad, change the field (or add an accessor), and recompile it against the original .jar. Then put the new .class ahead of the .jar in the classpath, or reinsert it in the .jar. (the jar utility allows you to extract and reinsert to an existing .jar)

    As noted below, this resolves the wider issue of accessing/changing private state rather than simply accessing/changing a field.

    This requires the .jar not to be signed, of course.

提交回复
热议问题