1. 程式人生 > >將 java 改寫成 beanshell 的經驗之談

將 java 改寫成 beanshell 的經驗之談

下面經驗僅僅針對 bsh for android 而談, PC 上 beanshell 無需這樣改。

public class TimeTest  改寫為閉包: TimeTest() 

閉包末尾新增語句 return this;

public static void main(String[] args) 改寫為: run()

最後新增
timetest = TimeTest(); // call 閉包 == new TimeTest()

timetest.run();

比如: TimeTest.bsh

import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

TimeTest()
{
   private static DateFormat fmt = new SimpleDateFormat("yy-MM-dd HH:mm:ss") ;
 
   /** UTC -> local Time 
    */
   public static String getLocalTimeFromUTC(String UTCTime){
      java.util.Date UTCDate = null ;
      String localTimeStr = null ;
      try {
         UTCDate = fmt.parse(UTCTime);
         fmt.setTimeZone(TimeZone.getTimeZone("GMT+8")) ;
         localTimeStr = fmt.format(UTCDate) ;
      } catch (ParseException e) {
         print(e);
      }
      return localTimeStr ;
   }

   run()
   {  
      Calendar cal = new GregorianCalendar();
      zone = cal.getTimeZone().getID();
      print(zone);
      Date date1 = new Date();
      time1 = fmt.format(date1);
      print("my 20"+time1);
      try
      {  
         Socket s = new Socket("time.nist.gov", 13);
         try
         {
            InputStream inStream = s.getInputStream();
            Scanner in = new Scanner(inStream);
            
            while (in.hasNextLine())
            {  
               String line = in.nextLine();
               // print(line);
               if (line.length() >24){                  
                  String UTC = line.substring(6,24);
                  print("UTC  "+UTC);
                  print("CN 20"+getLocalTimeFromUTC(UTC));
               }
            }
         }
         finally
         {
            s.close();
         }
      }
      catch (IOException e)
      {  
         print(e);
      }
   }

   return this;
}

timetest = TimeTest();
timetest.run();