今天学习fabric-sdk的时候,看到这样一段代码
// create a gateway connection
try (Gateway gateway = builder.connect()) {
// get the network and contract
Network network = gateway.getNetwork("mychannel");
Contract contract = network.getContract("fabcar");
//以下都是对账本进行的操作,并不重要
byte[] result;
contract.submitTransaction("createProject", "PROJECT003", "kkkk", "1", "kkksadas", "100","12","time");
Timestamp current = new Timestamp(System.currentTimeMillis());
contract.submitTransaction("createContribution","CONTRIBUTION000","1","PROJECT000","100",current+"");
contract.submitTransaction("updateProject","PROJECT000","100");
result = contract.evaluateTransaction("queryContributions","CONTRIBUTION000");
System.out.println(new String(result));
}
这个try后面加小括号的写法我还是第一次见,原来这是jdk1.7之后的新特性,括号里面的资源,会在try后面大括号里的内容执行完毕后自动释放。官方的注释
我们可以让类继承AutoCloseable接口,然后用使用try-with-resources block,将对象放到小括号里,这样当代码块执行完毕后,就自动释放小括号里的资源了。不过也提到在使用非I/O类对象时,这个东西不是很有必要