java : var 语法糖

阅读更多
jdk 10 据说要采用 var 语法糖,其实就是一个字符串替换游戏.
Clasz x = new Clasz(); // 可以简化成
var x = new Clasz(); // 减少了程序员的重复性输入
例如:这样写 java 伪代码 var_Client.java
import java.io.*;
import java.net.*;
import java.util.*;

public class Client {
	private String host;
	private int port;

	// 构造方法
	public Client(String host,int port){
		this.host=host;
		this.port=port;
	}
	// 连接方法
	public String connect(String msg){
		if (msg == null) return null;
		var sb = new StringBuffer(100);
		try {
			var socket = new java.net.Socket(host,port);
        	var writer = new java.io.PrintWriter(socket.getOutputStream(),true);
        	writer.println(msg);
        	try {
            	var ins = new java.util.Scanner(socket.getInputStream());
            	while( ins.hasNextLine()){
                	sb.append(ins.nextLine());
            	}
        	} finally {
            	socket.close();
        	}
    	} catch(IOException e){
        	return e.toString();
    	}
    	return sb.toString();
    }
    // Test
    public static void main(String[] args){
    	String msg =null;
    	if (args.length ==1){
    		msg = args[0];
    	} else {
    		System.out.println(" usage: java Clinet message ");
    		System.exit(1);
		}
		String host ="127.0.0.1";
		int port = 12345;
		var client = new Client(host,port);
		String str = client.connect(msg);
		System.out.println(str);
	}	
			
}

我用python写了一个字符串转换脚本 var_java.py
import os, sys

if len(sys.argv) ==2:
    f1 = sys.argv[1]
else:
    print 'usage: var_java.py var_Clasz.java '
    sys.exit(1)

if not os.path.exists(f1):
    print 'Error: %s not found\n' % f1
    sys.exit(2)

if not (f1.startswith('var_') and f1.endswith('.java')):
    print 'Error: %s is not var_*.java '
    sys.exit(3)

f2 = f1[4:]
if os.path.exists(f2):
    print 'Error: %s is exists\n' % f2
    sys.exit(4)

fp = open(f1,'r')
fp2 = open(f2,'w')
for line in fp:
    if line.strip().startswith('var '):
        i = line.find('new ',0)
        j = line.find('(',i)
        word =''
        if i < j:
            k = line[i+4:j].rfind('.')
            if k > 0:
                word = line[i+4+k+1:j]
            else:
                word = line[i+4:j]
        if len(word) >1:
            aline = line.replace('var ',word+' ',1)
        else:
            aline = line
    else:
        aline = line
    fp2.write(aline)
#
fp.close()
fp2.close()

运行 var_java.py var_Client.java 生成 Client.java
编译 javac Client.java 通过

你可能感兴趣的:(java,var,python)