考虑简单的例子
private static String isPositive(int val) {
if (val > 0) {
return "yes";
} else {
return "no";
}
}
Run Code Online (Sandbox Code Playgroud)
这里非常简单:如果val > 0
返回yes
,则返回no
.但是在编译之后,在字节码中,这个if条件被反转:
private static isPositive(I)Ljava/lang/String;
L0
LINENUMBER 12 L0
ILOAD 0
IFLE L1
L2
LINENUMBER 13 L2
LDC "yes"
ARETURN
L1
LINENUMBER 15 L1
FRAME SAME
LDC "no"
ARETURN
Run Code Online (Sandbox Code Playgroud)
它检查:如果val <= 0
然后返回no
,否则返回yes
.
首先,我认为<=
检查更便宜,而且它是某种优化.但是,如果我将我的初始代码更改为
if (val <= 0) {
return "no";
} else {
return …
Run Code Online (Sandbox Code Playgroud) 我有这个代码:
public static class MyWebDriver extends RemoteWebDriver {
@NotNull
private final String nodeId;
public MyRemoteWebDriver(@NotNull String nodeId) {
super();
this.nodeId = nodeId;
}
@Override
public void quit() {
System.out.println("deleting node: " + nodeId);
}
}
Run Code Online (Sandbox Code Playgroud)
并且保证nodeId
传递给构造函数的不是null
.因为nodeId
字段是final
我希望它在我的quit()
方法中初始化.
但是,在super()
构造函数中有一个try-catch
块,在异常调用 quit()
方法的情况下抛出异常.在这种情况下nodeId
,我进入我的quit()
方法没有初始化(null
有价值).
有没有办法避免它除外
@Override
public void quit() {
if (nodeId != null) {
System.out.println("deleting node: " + nodeId);
} …
Run Code Online (Sandbox Code Playgroud) 假设我有这个重要的方法:
int generateId(int clientCode, int dataVersion) {
return clientCode * 2 + dataVersion % 2;
}
Run Code Online (Sandbox Code Playgroud)
这两个参数都是int
,因此使用错误的参数来调用此方法非常容易,例如generateId(dataVersion, clientCode)
.它将被成功编译和执行.但生成的id将完全错误,这可能会导致严重的问题.
所以,我的问题是:有没有办法保护自己免受这种参数错位?
现在我只想把它int
改成包装类,如:
int generateId(@Nonnull ClientCode clientCode, @Nonnull Version version) {
return clientCode.getValue() * 2 + version.getValue() % 2;
}
static class IntWrapper<T> {
private final int value;
IntWrapper(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
static class ClientCode extends IntWrapper<ClientCode> {
ClientCode(int value) {
super(value);
}
}
static class …
Run Code Online (Sandbox Code Playgroud)