Groovy應用(基本操作)

一、Groovy基本操作

Base.groovy

package com.jlee

import java.text.SimpleDateFormat
import java.util.Calendar


/**
 * @author JLee
 *
 */
public class Base{

	public test(){
		"***************";
	}
	
	//	7、閉包
	def foo(temp){
		temp.call("closure parameter") ;
		temp.call([1,2].collect{it*2}) ;
	}
	
	public static void main(args){
		
		//1、單行單條語句可以不用寫“;”
		println "不用 分號 結尾"
		println "單行多條語句要有 分號"; println "但是建議不論什麼情況都加上 分號 結尾"
		
		//2、語句可以跨多行
		def arr = [1,
		       2,
		       3,
		       4];
		println arr ;
		
		//3、支持表達式
		String str = "Hello World".replaceAll("World","Groovy") ;
		println "new string is ${str}" ;
		
		//4、可以直接調用Java類
		def sdf = new SimpleDateFormat("yyyy-MM-dd") ;
		def date = sdf.parse("2011-11-22") ;
		def cal = Calendar.getInstance() ;
		cal.setTime(date) ;
		println "The Time is ${cal.get(Calendar.YEAR)}-${cal.get(Calendar.MONTH)}-${cal.get(Calendar.DAY_OF_MONTH)}" ;
		
		//5、定義方法的時候返回類型可以不寫(默認是Object),
		//並且可以不用寫 return,調用方法時可以不用括號如 println,
		//只要有參數且沒有歧義
		def sss = new Base().test() ;
		println sss ;
		
		//6、傳遞命名參數
		//只實現Map方法調用與JavaBean構造
		Bean bean = new Bean(id : "12123" , name : "JLee");
		//直接可以訪問 private 的 field
		println bean.id + "   " + bean.getName() ;
		
		//7、閉包
		def closure = { println it } ;
		new Base().foo(closure) ;
		
		//8、動態類型
		def dynamicType = [ name:"Jlee" , age:24] ;
		println dynamicType ;
		dynamicType = "*********" ;
		println dynamicType ;
		
		//9、Groovy中的 == 等於 Java 中的 equals
		// === 相當於 Java 中的 ==
		String string = "str" ;
		if(string == "str"){
			println "   ==    " ;
		}
		if(string.equals("str")) {
			println "    ===    " ;
		}
		
		//10、對於大段文字可以用三個引號來定義
		def longString = """ ssssssssssssssssssssssssssss """ ;
		println longString ;
		
		//11、".." 包含左右邊界
		//"..." 不包含右邊界
		def rang1 = 1..9 ;
		rang1.each{ print "${it}," ; };println "" ;
		println rang1 instanceof java.util.List ;
		
		Map map1 = [:]; //定義空Map
		Map map2 = [name:'JLee' ,sex:'男']; //定義Map
		println "map1 size ${map1.size()} , value : ${map1}" ;
		println "map2 size ${map2.size()} , value : ${map2}" ;
		
		println map2.get('name');
		map1.put("element" ,[1,2,3]);
		println "map1 size ${map1.size()} , value : ${map1}" ;
		
		//Groovy下標操作符的應用
		String stringStr = "abcdefghijklmnopqrst" ;
		List list = [1,2,3,4,5] ;
		def rangesRan = 6..9 ;
		Map mapmap = [element1:'222',element2:'333333'];
		println stringStr[2] ;
		println list[2..4] ;
		println mapmap['element1'] ;
		println list[-2] ;
		
		
		
		
		//static{println ''}不支持靜態塊
		//do{println "ddd" ;}while(true);不支持
		
		for(int i=0 ;i<10;i++){
			print i ;
		}
		def j=0 ;
		while(j==0){j++;println " ";}
		println false ? 'a' : 'b' ;
		
		//訪問數據庫
		String sqlStr = "select * from user ";
		def sql = groovy.sql.Sql.newInstance("jdbc:mysql://localhost/mysql","root","root","com.mysql.jdbc.Driver");
		sql.eachRow(sqlStr){
			row->
			println "${row[0]}, ${row.User}";
		};
		
	}
	
	
	
}

 

 

 二、Groovy與Java之間的相互調用

IFoo.java

package com.jlee;
/**
 * @author Jlee
 * @date 2011-11-19
 * @desc Java 接口
 */
public interface IFoo {
	 public Object run(Object foo);   
}

 Foo.groovy

package com.jlee ;
import java.lang.Override
/**
 * @author Jlee
 * @date 2011-11-19
 * @desc 實現Java 接口的 Groovy 類
 */
public class Foo implements IFoo {
	@Override
	 public Object run(Object foo){
		 println 'Hello World!' ;
		 /*******************************
		  * 實例化Java實現Foo接口的Foo2類*
		  * Groovy中調用Java                      *
		  * ******************************/
		 Foo2 f2 = new Foo2() ;
		 def str = f2.run(2);
		 println str ;
		 return foo*10;
	 }	
	 //直接運行該Groovy類
	 public static void main(args){
		 Foo f = new Foo();
		 f.run(3)
	 }
}

 

Foo2.java

package com.jlee;
/**
 * @author Jlee
 * @date 2011-11-19
 * @desc 實現Java 接口的 Java 類
 */
public class Foo2 implements IFoo {

	public Object run(Object foo) {
		System.out.println("Foo2裏面輸出 : "+foo);
		return "foo2";
	}

}

 

InvokeGroovy.java

package com.jlee ;

 import groovy.lang.GroovyClassLoader;  
 import java.io.File;  
 /**
  * @author Jlee
  * @date 2011-11-19
  * @desc Java調用Groovy
  */
 public class InvokeGroovy {   
   
     public static void main(String[] args) {  
         ClassLoader cl = new InvokeGroovy().getClass().getClassLoader();  
         GroovyClassLoader groovyCl = new GroovyClassLoader(cl);  
         try {  
             Class groovyClass = groovyCl.parseClass(new File("src/com/jlee/Foo.groovy"));  
             IFoo foo = (IFoo) groovyClass.newInstance();  
             System.out.println(foo.run(new Integer(2)));  
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
     }  
   
 }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章