动静结合的语言?

静态类型和动态类型各有长短,为何不让这2者兼得呢?

比如一段代码:
String str = "Hello, World";
dynamic str1 = str.substring(7);
dynamic str2 = str1.toLowerCase();
dynamic str3 = str2.toUpperCase();

只需要一个关键字表明它是一个动态类型,并给它加上一个wrapper类,然后把方法调用扩展成一个send方法,我假想的编译器展开后结果是这样的:
String str = "Hello, World";
Dynamic str1 = new Dynamic(str.substring(7);
Dynamic str2 = new Dynamic(str1.send("toLowerCase"));
Dynamic str3 = new Dynamic(str2.send("toUpperCase"));

剩下的工作好办了,只要支持反射的语言都可以完成。

完整测试代码:
class Dynamic{
	private Object object;
	
	public Dynamic(Object object){
		this.object = object;
	}
	
	public Object send(String methodName, Object ... args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
		Class[] classes = new Class[args.length];
		for(int i=0; i<args.length; ++i)
			classes[i] = args[i].getClass();
		Method method = object.getClass().getMethod(methodName, classes);
		return method.invoke(object, args);
	}
	
	public String toString(){
		return object.toString();
	}
}

public class Test {

	public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		String str = "Hello, World!";
		Dynamic str1 = new Dynamic(str.substring(7));  // dynamic str1 = str.substring(7);
		System.out.println(str1);
		Dynamic str2 = new Dynamic(str1.send("toLowerCase"));  // dynamic str2 = str1.toLowerCase();
		System.out.println(str2);
		Dynamic str3 = new Dynamic(str2.send("toUpperCase"));  // dynamic str3 = str2.toUpperCase();
		System.out.println(str3);
	}
}

你可能感兴趣的:(velocity,JSF,脚本,嵌入式,Ruby)