问题:jar依赖环境下,被依赖的库中的枚举类如果调整枚举顺序会对依赖者产生什么影响? 只所以问这个问题,是因为我不确定枚举项会不会编译到依赖者bytecode的常量区里。如果会,则被依赖库的修改影响不到依赖者。
答案是:依赖者将完全参照被依赖者里的定义来行事,不存在常量区的问题。
============================场景一:先Hello,再World=============================
b.jar里面有个枚举EnumInB.java
public enum EnumInB {
HELLO("Hello"), WORLD("World");
private String displayText;
private EnumInB(String displayText){
this.displayText = displayText;
}
public String getDisplayText() {
return displayText;
}
}
a.jar依赖b.jar,且其中有个类依赖了EnumInB
让它打印一下各个枚举项的值
public class PlayEnumInB {
public static void main(String[] args) {
System.out.println(EnumInB.HELLO.name() + "-" + EnumInB.HELLO.getDisplayText() + "-" + EnumInB.HELLO.ordinal()); //HELLO-Hello-0
System.out.println(EnumInB.WORLD.name() + "-" + EnumInB.WORLD.getDisplayText() + "-" + EnumInB.WORLD.ordinal()); //WORLD-World-1
}
}
============场景二:先World, 再Hello===============================================
调整一下枚举里的顺序
这时调整一下EnumB里枚举里的顺序,并重新编译b.jar
WORLD("World"), HELLO("Hello");
}
依赖者的表现
a.jar更新b.jar的版本,但不重新编译a.jar
System.out.println(EnumInB.HELLO.name() + "-" + EnumInB.HELLO.getDisplayText() + "-" + EnumInB.HELLO.ordinal()); //HELLO-Hello-1
System.out.println(EnumInB.WORLD.name() + "-" + EnumInB.WORLD.getDisplayText() + "-" + EnumInB.WORLD.ordinal()); //WORLD-World-0
==============场景三:Hello, World改变属性===============================================
改变一下枚举里面的成员属性
HELLO("HelloHello"), WORLD("WorldWorld");
}
依赖者的表现
System.out.println(EnumInB.HELLO.name() + "-" + EnumInB.HELLO.getDisplayText() + "-" + EnumInB.HELLO.ordinal()); //HELLO-HelloHello-0
System.out.println(EnumInB.WORLD.name() + "-" + EnumInB.WORLD.getDisplayText() + "-" + EnumInB.WORLD.ordinal()); //WORLD-WorldWorld-1
}
}