如果引用或轉貼,麻煩註明出處與本網誌連結,否則視為侵權。
顯示具有 Java 標籤的文章。 顯示所有文章
顯示具有 Java 標籤的文章。 顯示所有文章

2016年3月2日

Java基本資料型別轉換

原始發文日 :2005/7/1 , 修訂: 2011/11/3, 2016/3/2 作者 : Fred Wang

這是一些簡單常用的Java基本資料型別轉換
1.數字轉字串
1.1 整數轉字串 integer to String 
int i = 20;
String str = Integer.toString(i);
or
String str = String.valueOf(i);
or
String str = "" + i;

1.2 雙精度數字轉字串 double to String :
double d = ...;
String str = Double.toString(d);
or
String str = String.valueOf(d);

1.3 長型態數字轉字串 long to String :
long l = ...;
String str = Long.toString(l);
or
String str = String.valueOf(l);

1.4 浮點型態數字轉字串 float to String :
float f = ...;
String str = Float.toString(f);
or
String str = String.valueOf(f);

2.字串轉數字
2.1 字串轉整數 String to integer :
String str = "20";
int i = Integer.valueOf(str).intValue();  //第一種方法, ValueOf會傳回一個Integer物件
or
int j = new Integer(str).intValue(); //第二種方法
or
int k = Integer.parseInt(str);  //第三種方法

2.2 字串轉雙精度數字 String to double :
double d = Double.valueOf(str).doubleValue(); 
or
double d = Integer.parseDouble(str);  


2.3 字串轉長型態數字 String to long :
long l = Long.valueOf(str).longValue();
or
long l = Long.parseLong(str);

2.4 字串轉浮點型態數字 String to float :
float f = Float.valueOf(str).floatValue();
or
float f = Float.parseFloat(str);

3.十進位,二進位,八進位與十六進位數字的轉換
3.1 十進位轉二進位 (decimal to binary)
int i = 20;
String binstr = Integer.toBinaryString(i);

3.2 十進位轉十六進位 (decimal to hexadecimal)
int i = 20;
String hexstr = Integer.toString(i, 16);
or
String hexstr = Integer.toHexString(i);
or (含前置零與大寫 with leading zeroes and uppercase)
public class Hex {
  public static void main(String args[]){
  int i = 20;
  System.out.print(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
  }
} 

3.3 十進位轉八進位 (decimal to octal)
 int i = 20;
String octstr = Integer.toString(i, 8);
or
String octstr = Integer.toOctalString(i);


3.4 十六進位轉整數 (hexadecimal (String) to integer)
int i = Integer.valueOf("B8DA3", 16).intValue();
or
int i = Integer.parseInt("B8DA3", 16);

4. ASCII Code的轉換
4.1 ASCII碼轉字串 (ASCII code to String)
int i = 64;
String aChar = new Character((char)i).toString();

4.2 整數轉ASCII碼 (integer to ASCII code (byte))
char c = 'A';
int i = (int) c;  // i 的值會轉成 65

4.3 從字串擷取ASCII碼 (To extract Ascii codes from a String)
String test = "ABCD";
for ( int i = 0; i < test.length(); ++i ) { 
   char c = test.charAt( i ); 
   int i = (int) c; 
   System.out.println(i); 
}  

5.布林(Boolean)值的轉換
5.1 整數轉布林值 (integer to boolea)
b = (i != 0);

5.2 布林值轉整數 (boolean to integer)
i = (b)?1:0;

5.3 布林值轉字串 (boolean to string)
String str = String.valueOf(b);


6.數字轉換的錯誤處理

使用try/catch來捕捉轉換過程的錯誤
try{
       i = Integer.parseInt(aString);
}  catch(NumberFormatException e) {

}

7.日期與字串的轉換 
7.1 日期時間轉字串 : 顯示預設完整的日期時間格式, 例如 Wed Nov 05 12:05:06 EST 2003
Date dNow = new Date(); 
String sNow = dNow.toString();
 
7.2 日期轉字串 Date to String : 顯示特定的日期格式

方法一日期轉成指定格式的StringBuffer, 再將StringBuffer轉成String
Date dNow = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
StringBuffer sbNow = new StringBuffer();
// 將日期dNow以"yyyy-MM-dd"的格式轉存到StringBuffer sbNow中
sbNow = formatter.format(dNow, sbNow, new FieldPosition(0));
// 將StringBuffer轉成String
String sNow = sbNow.toString();

方法二 日期直接轉成指定格式的字串(String) --比較簡單
Date dNow = new Date(); 

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String sNow = formatter.format(dNow)

7.3 字串轉日期 String to Date
String sDate = "2005-01-01";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dDate = formatter.parse(sDate,new ParsePosition(0));

8.數字型態間的轉換
8.1 由短數字型態轉換成長數字型態 (擴大轉換)
如byte 轉成 short, int, long, float, 或 double,short轉成int, long, float, or double, char轉成int, long, float, or double, int 轉成 long, float, or double, long轉成float or double, float轉成double
(數字型態由短至長的順序為 byte, short or char, int, long, float, double)

直接指定就可以自動轉換 !
例 :
int a = 50;
long b = a; // widening conversion

8.2 由長數字型態轉換成短數字型態 (縮小轉換,又稱為Casting)
例 :
long a = 100000000L;
int b = (int) a; // narrowing conversion

但是長數字型態的內容長度如果超過較短數字型態可容納的長度,雖然編譯與執行都不有錯誤訊息,但是會造成資料loss的現象。(這種隱含的錯誤,不容易debug,要特別留意)

2012年3月7日

Java重構工具(Refactoring Tools)整理

作者: Fred Wang (FW知識瑣記) 日期: 2012/3/7, revised 2012/4/5

網路上許多重構工具版本都相當老舊,也沒有新板產生。早期一些重構工具的網站也已經關閉了。下面是一些現存Java重構工具的整理 :

1. Eclipse提供的20多個重構功能
image
2.RefactorIT : 自動化重構, 原始碼衡量, 稽核與修正。可以單獨安裝或作為Eclipse與NetBeans開發環境的插件(Plug-in) ,Open Source :
http://sourceforge.net/projects/refactorit/

3.JFactory : 提供15種重構能力的工具,可以單獨執行,直接下命令列或作為JBuilder, NetBeans與Elixir IDE的插件。 Open Source : http://jrefactory.sourceforge.net/

4.Transmogrify : Java程式碼分析與重構工具
. Open Source :
http://transmogrify.sourceforge.net/

5.DPT(Design Pattern Transformer) : 研究用途的工具,提供prototype工具,以利對Java程式碼重構的設計與了解。 Free : http://dpt.kupin.de/

6.JavaRefactor : 小型的Java程式碼重構工具,為JEdit的插件。(http://plugins.jedit.org/plugins/?JavaRefactor)

2012年1月30日

J2EE系統修改(進化)之規劃案例

作者: Fred Wang (FW知識瑣記) 原作日期:2004/05/27

這是筆者2004年針對某一老舊的J2EE系統進行檢討與改版的規劃

 1.單元測試及除錯
   a.導入JUnit

 2.功能上的錯誤

3.設計上的提升
  • 選單展開及縮合設計
  • 欄位長度不正確, 輸入欄位要加maxlength
  • UI 專業化的設計
  • 輸出報表改為Excel格式
  • 前端一致性的設計(common button lines)
 4.功能上的提升

5.平台的升級

   a.改以IDE平台開發

6.程式設計方法的提升

    a.JSP : Javascript共用的部分寫成external js檔

    b.JSP : 改用include架構檔的方式, 將框架設計存成上方及下方兩組框架檔

    c.JSP : 新增及修改共同欄位及javascript 取出到一個included file, 以利維護

    d.JSP and Java :用Dispatch action合併相關的 Action

  • change struts-config.xml : action mapping
  • change form-bean : add attribute “method” and getMethod(), setMethod()
  • change configurations : Page and ViewMetaData

   e.JSP and Java : 採用struts-html tags and transfer data by form (不透過session attributes)

   f.JSP and Java : 加強exception handling

    g.JSP : selection-options改用html:optionsCollection

7.重構 – 除去不良的設計方法

   a.讓程式清楚易懂(Abstraction) : Extract Method,….

   b.去除重複的程式碼(Reusability) : Extract Method,…. Connection方法

   c.減少程式碼 : inline Temp,….

2011年11月7日

Java程式審查清單(code review checklist)

譯者 : Fred F.M. Wang 日期 : 2011/11/14

以下是一些審查 Java程式碼需注意項目。以下清單有審查 Java程式碼要展開的活動列表。包含有11個不同類型的問題與審查的領域。譯者註 : 有許多也不限於Java程式,在多數語言都適用,有些部份也可以利用Code Review或inspection工具輔助檢查,有些則需人工檢查。 
1. 程式設計風格與樣式相關問題
1.1 有遵循專案計劃中指定的標準?
1.2 有提供適合的內含文件,也就是程式內的註解? 以提供較佳的可維護性。 
1.3 程式檔案開頭是否包含下面項目
  • 程式標頭 : 如程式名稱與描述
  • 應用系統名稱 
  • 依存關係 : 相關的程式,Tables等 
  • 限制 : 執行環境與條件 
  • 版權資訊 
  • 修改日誌
1.4 是否遵守有意義的命名慣例?命名是否正確反映程序或參數層級?命名是否正確定義全域,共用與外部的功能函式?譯者註 :以提高程式的可讀性。
1.5 程式碼是否有做合適的縮排? 譯者註 :以提高程式的可讀性。
1.6 是否呼叫一套共用的副程式庫,而不是複製程式碼到不同的程式中? 譯者註 :以提高程式的再用性,與可維護性。
1.7 有任何冗餘的程式碼? 譯者註 :應該撰寫乾淨的程式碼(Clean Code)。透過版本管理軟體保留舊版程式,而不要把舊程式碼mark成註解保留在程式中造成冗長且難以閱讀的程式。
2. 標籤和助譯碼相關問題
2.1 程式中有任何標籤(label)沒有被引用到?
2.2 是否使用有意義的助譯碼或巨集? (助譯碼通常用於設定畫面選單或其他操作的快速鍵)
2.3 助譯碼或巨集是否正確地使用。
3. 陣列相關的問題
3.1 所有的陣列索引值是否會落在限定範圍(bounds)內? 譯者註 :程式中應該做陣列索引值檢查,避免在執行中超過限定範圍(bounds),造成不可預期的錯誤。
3.2 是否正確地初始化所有陣列的索引?
4. 迴圈/分支相關的問題
4.1 所有分支條件是否正確?
4.2 迴圈是否可被終止? 譯者註 :除了極少數的情況,程式迴圈都應該可以被終止。
4.3 終止一個迴圈的條件是否正確?
4.4 程式中除法運算式前,是否有檢查除數為零的狀況?
4.5 放在迴圈內的敘述是否可以移到迴圈外? (譯者註 :避免效能問題)
5. 結構相關的問題
5.1 某些部分的程式碼,在程式各種執行的線程中,是否永遠不會被執行到?  譯者註 :不會被執行到的程式碼就是冗餘的程式碼,也有可能是程式的條件式設計錯誤。
5.2 是否使用了過多的IF敘述? 譯者註 :是否可以用Switch.. Case語法取代多重的IF敘述? 以提高程式的可讀性。
6. 功能相關的問題
6.1 程式中對匯入的資料是否有做正確性檢查?
6.2 呼叫程式碼(Caller)實際參數與被呼叫的副程式中的正規參數是否匹配?
6.3 所有變數是否都有被使用到? 所有輸出的變數是否都有指定值? 譯者註 :這種情況容易造成程式維護者的困擾,因此程式開發時就應該去除沒有被使用到的變數,以提高可維護性。
7. 資料庫相關的問題
7.1 是否對Table的query有使用索引? (譯者註 :Select * Where.. 的query中如果沒有對應的索引,將造成全表搜尋,影響執行效能)
7.2 新增/修改模式的畫面屬性是否正確的設定與重設?
7.3 每個SQL敘述後是否有做錯誤狀態的檢查?
7.4 在更新資料庫data record前是否有先進行data record的鎖定(lock)
7.5 運算式中下面兩個條件是否有檢查?
  • Rounding off (if required) 四捨五入(如果需要)
  • Possibility of division by zero 除以零的可能性
8. 效能相關的問題
8.1 是否滿足執行時間的需求? 要做效能測試!
8.2 是否有更有效率的寫法? 譯者註 :例如相同結果採不同SQL寫法效率差異很大,因此有些SQL最佳化工具用來改善SQL Code。
9. 可用性相關的問題
        程式處理需要花較長的時間,是否提供通知訊息(optional)? 譯者註 :例如提供進度列(progress bar),讓使用者需要花多少時間? 還有多久才會執行完? 避免讓使用者有系統當掉的不安感。
10. 檔案相關的問題
     檔案處理是否有做下面的檢查?
  • 開啟檔案時先檢查檔案是否是空的?  
  • 檢查是否產生輸出入的錯誤?
11. 錯誤處理的問題
11.1 使用者對錯誤訊息容易理解嗎? 錯誤訊息合適嗎?
11.2 所有的錯誤有被捕捉與控制嗎? (譯者註 :避免當掉的情況)
參考原文 : http://technotes.towardsjob.com/java/code-review-checklist-for-java/




2011年11月4日

Google免費提供的Java GUI開發工具,測試工具,程式品質與安全分析工具


2010/12/17 Google捐贈價值五百萬美金開發工具給Eclipse基金會
ZDNET新聞專區: Ed Burnette
2010/12/17
”前Instantiations產品開發副總裁現任Google軟體經理Eric Clayberg在Google Code
部落格上宣布,Google將捐贈WindowBuilder及CodePro Profiler這兩套開發工具的原
始碼及IP給予Eclipse基金會。
WindowBuilder是Google在今年8月併購Instantiations公司時所獲得的技術,是目前
最好的Java圖形介面設計工具;而CodePro Profiler則是可讓Java效能最佳化的工
具。估計這兩項工具的價值在5百萬美金左右。
Google也計畫將這兩項產品的支援轉由其他廠商來提供。在WindowBuilder支援部分預
計將由Genuitec提供,而CodePro Profiler將由OnPositive公司提供。從這些服務合
約獲得的營收將可用來支付部分人員的薪水。”

包含下面三項工具
1. WindowBuilder Pro
Develop Java graphical user interfaces in minutes for Swing, SWT, RCP, XWT and GWT with WindowBuilder Pro’s WYSIWYG, drag-and-drop interface. Use wizards, editors and intelligent layout assist to automatically generate clean Java code, with the visual design and source always in sync.
強大的GUI開發工具,可以讓Java開發者以所見即所得的介面,使用Swing, SWT, RCP, XWT, Google Web Toolkit(GWT)快速地建構用戶界面。
2. WindowTester Pro
Streamline testing of Java rich client applications with WindowTester Pro, including tools for automated recording, test generation, code coverage and playback of GUI interactions that can occur within an application. WindowTester Pro includes support for SWT and Swing.
在Java Rich Client應用中,針對SWT和SwingUI框架,測試GUI互動的工具,包含錄製 工具,測試產生器等。3. CodePro AnalytiX (CodePro Profiler)
Employ the comprehensive automated software code quality and security analysis toolkit CodePro AnalytiX to automatically improve software quality, reliability, and maintainability in developer applications.
綜合性 的自動化軟體程式品質和安全分析工具,以改善軟體品質、可靠性和可維護性。
下載點 http://code.google.com/javadevtools/download.html (這些是Eclipse plug-ins)

2011年10月30日

如何用Netweaver Developer Studio開發Struts架構的應用系統

 

Fred Wang(http://fredwang.blogspot.com) 原作日期 : 2004/12/28

前言

如果對Eclipse(http://www.eclipse.org/)熟悉的人就會發現SAP Netweaver Developer Studio(http://www.sap.com/solutions/netweaver/index.aspx) 繼承自Eclipse的血統, 因此這篇文章也適用於用Eclipse來開發Struts應用系統。

使用環境

IDE : SAP Netweaver Developer Studio 2.08

Plugin : Struts Console 4.5 (http://www.jamesholmes.com/struts/console/) , 提供Struts configuration file(struts-config.xml)編輯的功能, 目前最新版為4.8, 應該都可以使用。

Web Server : BEA Weblogic Server 8.1

進入SAP Netweaver Develooper Studio

Create a Web Project

Steps :

1. File –> New –> Web Module Project.

2. Enter a project name (ex: ts2WebProject ), press [Finish]

3. Set Project Properties : point to project name and click mouse right key, then choose “Properties”, 畫面如下 :

clip_image002

4. 將下載後的Struts解壓縮到一個目錄, 到上面Properties畫面的Java Build Path, 右方畫面選Tab “Libraries”, 按”Add External Jars” button, 將Struts所有的Jar檔選入

5. 同一畫面, 選Tab “Order and Export”, 將選入的jar, 逐一設定v, 按[OK]

6. 將ActionServlet加入web.xml : 在左邊的J2EE Explorer視窗中的Servlet Candidates找到ActionServlet, 按滑鼠右鍵, 選”Add to web.xml

clip_image004

然後在右方web.xml編輯視窗中,

a. 在Tab “Web Objects” 中, 新增ActionServlet的init-

parameter, 加入三組參數 (name, value)

. config , /WEB-INF/struts-config.xml

. debug, 4

. validating : true

b. 在Tab “Mapping” 中,新增Servlet mapping, 選 ActionServlet, 輸入 *.do

c. 在Tab “Others” 中, 加入Tag-libs and Welcome pages

7. 在Navigator視窗中, 將struts-config.xml, *.tld 檔放在WEB-INF內 (struts-config.xml可以用一些open source tools來建立)

撰寫程式

1. 建立Web Pages: 在Navigator視窗中選WebContent, 按滑鼠右鍵New Jsp

2. 建立form beans : 在Navigator視窗中選source , 按滑鼠右鍵New class

3. 在struts-config.xml註冊form beans

4. 建立action class: 在Navigator視窗中選source , 按滑鼠右鍵New class

5. 在struts-config.xml撰寫action mappings

Create Web Archive

選定Web Application, 按滑鼠右鍵, 選Build Web Archive

2011年10月22日

[Java基本觀念] Java各種變數型別的記憶體儲存區域

 

作者 : Fred (Hainchu-Taiwan) 原作日期:2004/11/8

image

JSP and Struts開發經驗

 

作者 : Fred (Hainchu-Taiwan) 原作日期:2005/1/3

JSP

  • JSP程式的錯誤難以測試
  • JSP程式混合多種語法,包含HTML,JSP script,Java,Javascript, CSS
  • 發生錯誤時執行期才會顯示出來
  • 執行期產生的錯誤訊息顯示錯誤的程式行數並非JSP的程式行數,而是Web Server將JSP翻譯成Servlet後的程式行數,如果用Tomcat做Web Server還可以找到翻譯後的Servlet程式,但是其他Web Server可能就沒有了。

因應之道

  • 盡量簡化JSP的程式碼,避免複雜的邏輯,盡量是單純的HTML
  • 減少java scriptlet的使用
  • 利用Tag library,如Struts tags, JSTL tags

 

Jakarta Struts

Struts Tag的使用要嚴格檢查

  • HTML是給Web browser讀的,而這些browser由容錯機制,因此HTML寫錯或starting tag and closing tag不搭配時也不會造成無法執行的嚴重錯誤,但是Struts tags會經由web container及API解譯,如果有錯就會造成編譯的錯誤,而無法執行,因此這點是要特別注意的。

Struts Tag 並非標準

  • 建議採用JSTL取代Struts相關的Logic, Bean等tag library,只保留struts html tag for Action Form bean的使用。
  • 盡量使用ForwardAction以減少Java程式的數量
  • 透過ForwarAction可以將許多存取對象(Domain object)相同的action集合到同一個class內處理。如此不但減少維護的程式量也可以撰寫helping method將共同的程式碼extract成共用的method。

2005年12月27日

推薦文章 : 開放原始碼 + Java = 省錢專案

David Berlind原著‧陳奭璁譯  2003/02/06 (摘自Taiwan.CNET.com)

http://www.zdnet.com.tw/enterprise/technology/0,2000085680,20065321,00.htm

這篇文章非常好,如何解決因內部各種異質IT基礎設施與OS專用的老舊程式阻礙公司進步? 如何讓系統間相容,容易整合? 整理為下面四部份

1.每個平台商業邏輯都必需經過標準化,以便與其他平台作溝通, 例如採用Java當作商業邏輯層


2.選擇一個整合開發平台,一體適用在整個基礎設施上

3.加入一層界面來作統一的呈現,例如用Web為統一的呈現層。

4.選擇適用於各個部分的開放原始碼元件包括IDE、Web伺服器、J2EE伺服器等。

2005年12月23日

Java繼承結構中建構子的注意事項

本例中Panda及Koala新增一個物件, 其成員變數count會加一, 但是執行結果Bear的count也會計數, 為何會這樣?

原因 :
程式編譯時Java都會自動在所有類別的建構子(Constructor)的第一行加上super()來呼叫父類別的建構子
因此下面例子中不但Koala, Panda的count會計數, 連父類別Bear的count也會計數Koala為1, Panda為3, Bear為4

2005年12月22日

Java多型在member variable與method的差異


一個物件的成員變數(member variable), 是存取自物件所宣告的Class
本例中物件b, 被宣告為Bear, 因此b.name的內容為Bear成員變數name的內容
但是呼叫此物件的方法(method), 則是執行自此物件實體的Class
本例中物件b,實體的Class為Koala, 因此b.name()將執行Koala的name()

2005年12月20日

[超基本] Java顯示1到100的質數

方法一 : 用boolean值控制


方法二 : 用continue控制, 程式效率更好!

2005年12月11日

[觀念筆記]多型的觀念與實用範例

多型的目的在於 "實作與介面分離" ,

一般多型是應用在繼承的關係裡面, 假設甲寫好一個 Base class 給大家拿來extends , 我們拿到這個 Base class 之後,會在新的 subclass 中去 override base class 的 method ,甲寫的 base class 基本上可以被視為是一種 interface (概念上的), 其他人寫的subclass 中的 method 則是實際 implementation 的部份 (你可以假設甲的 base class 中完全沒有任何 method 的 implementation )這樣一來, 外界只需要知道 甲的 base class 中定義的 method 有那些, 不必管是如何 implement

再舉個更實際的範例, Collection 這個概念, collection 在JDK 裡面其實是個 interface, 像是 vector ,stack 這些東西都是去 implement collection 這個interface .

當我們在寫程式的時候, 可以這樣寫 :

Vector c = new Vector();

另外可能會有一個 method (別人寫的) 它的格式是這樣的

public void test (Vector c) {
......
}

別人寫的這個 method 嘗試著要把我們宣告的 vector object 當作參數傳進去, 試著想想看, 如果當有一天我們要從 Vector 改用其他的資料結構如 stack, 會付出多大的 effort ?

除了修改我們自己的 code, 我們必須去修改所有把我們的 vector object當作參數的 method ~~~

這個時候多型就派的上用場了 :-) 如果別人程式是這樣寫的:

public void test(Collection c) {
......
}

直接把最高層的 interface / class 拿來當作參數, 那麼我們要從 vector 改成stack 只要做一件事情 :

Collection c = new Stack();

就是這麼簡單,

當別人的 method 接收到 c 這個 "reference variable", c 會去自動連結對應的subclass 及其 method (或是 implement 此 interface 的 class)

也就是說, 外界的人根本不必 care 我們實作的方式改變與否, 它們只要跟 base class (interface) 溝通即可~~

如此一來便達成 "實作與介面分離" 的目的囉 ~~

另外補充一下, 所謂的 interface 是可以拿來宣告 "reference variable" 的, 也就是像 Collection c ; 這樣做,但是後面要實際 new 一個 object instance 出來, interface 就做不到了, 它雖然也是class 的一種, 但是 interface 裡面根本沒有任何實作 ~~~

所以後面應該接 implement 此 interface 之 class 的 constructor (Vector, Stack 均 implement Collection interface)

Author : Silver

[觀念筆記]Java 存取修飾子 protected 與 default的差別

作者 : Fred Wang 日期 :2005/12/11  修訂日期 : 2013/5/26

private methods 只能在同一個class存取
default methods(不加修飾子) 同個package內的class 都可以存取or繼承

下面範例顯示五種變數存取權,i1是private, i2是default, i3是protected, i4是public, i5是method中的local變數,同一個package中class Base中的i1無法被子class j0302中的method讀取,default, protected與public都可以
























protected 具有 default 的權限, 不同之處在於, 如果"subclass"(如上例中的j0302)與主class(如上例中的Base)在不同的package中, default 就無法讓subclass存取了,  protected與public才可以

假設甲寫好一個Base class, 放在 com.free.util 的package裡面,在此 class 中的變數與methods 有 default 與 protected 兩種

現在乙另一個名為com.free.app1的package中寫一個 class j0302 要繼承(extend)甲寫好的 Base class, 在此 subclass 中, 僅能去存取Base class中 protected形態的methods與變數, 對於 default形態的methods 與變數是無法使用的 !

所以結論是 : 當您撰寫一個 class, 希望有一些 methods與變數不要給所有人用(public才是給所有class都可以用), 僅給會繼承(extend) 此類別的 subclass 使用 (此 subclass 可能位於相同或不同的package中) 請將這些 methods 與變數設成 protected

2005年11月29日

OpenCMS與Struts結合是很容易的

From http://www.opencms-forum.de/viewtopic.php?t=684&sid=34de0ed0c1e9f5b624b218e38d8b0d7d

內容如下:
To use struts in unison with OpenCms is very simple.

Everything is the same EXCEPT!

* Your jsps are in OpenCms
* In your struts-config.xml, when your doing a forward include the OpenCms servlet and the full path to the file within the VFS. So all
your forwards to jsp's would begin with /OpenCms/directories-in-vfs/the-file-in-vfs.jsp. Remember that OpenCms is "JUST" a servlet. So your really doing a forward to the opencms servlet with parameters (sorta). The paramaters being the path to the file in the vfs.

Setup your web.xml with both the OpenCms servlet and the struts servlet. Put in all the tag libraries that you need from both. And
that's it, you'll have all the advantages of managing your pages in OpenCms and all the mvc capabilites of struts.

The struts-OpenCms sourceforge project was attempting to put actions, actionforms, and all the configs files and jars in the VFS. IMHO I
don't think that's a good idea.

The approach I mentioned, just puts the JSPs in the VFS so it requires NO code changes to OpenCms or Struts.

2005年11月24日

[超基本] Java Static and non-Static


重點: Class 未被初始化(New instance)以前靜態方法(static method)只能存取靜態變數(static variable) 與區域變數 local variable
如下面範例 c2,c3,c4,c5無法被static method - main所存取


public class j0227 extends Object {
    static int c1=5; // 靜態變數
    public int c2=6;
    private int c3=7;
    final int c4=8;
    int c5=0;

    public static void main(String args[]) {
        int c6=4;  // 區域變數
        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);
        System.out.println(c4);
        System.out.println(c5);
        System.out.println(c6);
    }
}


/*
產生compile error如下:
E:\JavaExercise\Fred>javac -d . j0227.java
j0227.java:10: non-static variable c2 cannot be referenced from a static context
System.out.println(c2);
^
j0227.java:11: non-static variable c3 cannot be referenced from a static context
System.out.println(c3);
^
j0227.java:12: non-static variable c4 cannot be referenced from a static context
System.out.println(c4);
^
j0227.java:13: non-static variable c5 cannot be referenced from a static context
System.out.println(c5);
*/

結果靜態方法main()只能讀取靜態變數C1與區域變數C6。

 
同樣,Class 未被初始化(New instance)以前靜態方法static method(如main)不能直接呼叫非靜態方法non-static method。

public class TypeConversion {
    public static void main(String[] args){  // 靜態方法 main()
        int a = 10;
        long b = testConvert(a);    // 因為class TypeConversion 尚未初始化,因此會產生錯誤
        System.out.println(b);
    }

    long testConvert(long a) {  // 非靜態方法
        return a;
    }
}

靜態方法main()無法直接呼叫非靜態方法testConvert(),會產生錯誤。

只要改成這樣就可以了
(1)
public class TypeConversion {
    public static void main(String[] args){
// 靜態方法 main()

         int a = 10;
        TypeConversion1 t = new TypeConversion(); // 加上這行用來產生初始化物件
        long b = t.testConvert(a);  // 呼叫此物件的方法
        System.out.println(b);
    }

    long testConvert(long a) {  // 非靜態方法
        return a;
    }
} 

為該非靜態方法所在的class建立初始化物件,再用該物件呼叫該非靜態方法。

 
或
(2)
public class TypeConversion {
    public static void main(String[] args){
        int a = 10;
        Conversion c = new Conversion();  // 建立另一個class "Conversion"的初始化物件
        long b = c.testConvert(a);   // 呼叫這個物件的方法
        System.out.println(b);
    }
}

class Conversion {    // 將該非靜態方法放在另一個class
    long testConvert(long a) {
        return a;
    }
}

[超基本] Java Timer程式範例

分成三部分TimerService class程式, 被TimerService 定時驅動執行的程式, 啟動,停止或設定Timer Service的JSP程式

程式一 TimerService class程式

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
public class TimerService {
Timer timer = new Timer();
public TimerService() { };

public void start() throws Exception {

Calendar date = Calendar.getInstance();
date.setTime(new Date());
date.add(Calendar.DAY_OF_MONTH,1); // 驅動此程式的後一天
date.set(Calendar.AM_PM,Calendar.AM); // 上午
date.set(Calendar.HOUR,11); // 11點
date.set(Calendar.MINUTE,0); // 0分
date.set(Calendar.SECOND,0); // 0秒
date.set(Calendar.MILLISECOND,0); // 0毫秒

// timer.schedule(param1,param2,param3)
// param1: 就是要定時驅動執行的程式
// param2: 設定開始執行的時間,如上面的Calendar設定
// param3: 執行間隔時間(單位: 毫秒)
timer.schedule(
new DailyRun(),
date.getTime(),
1000 * 60 * 60 * 24
);
} // end of method

public void stop() throws Exception {
timer.cancel();
} // end of method
} // end of class

程式二 被TimerService 定時驅動執行的程式
public class DailyRun extends TimerTask {
public DailyRun() {
}

public void run() {
// 這裡是要執行的程式內容
} // End of method

} // end of class



另外要寫一支JSP來啟動與關閉Timer Service, 或者可以將執行時間與間隔透過JSP進行設定

相關文章:  使用標準的Java Timer API執行Scheduled Job



2005年11月23日

[超基本] Java Exception訊息的傳遞

作者 : Fred Wang 日期 :2005/11/23
在Multi-pier的J2EE程式設計,往往層次過多, 而難於除錯,通常會用Exception來將訊息傳到顯示端,來判斷錯誤點, 下面範例為Exception訊息如何由被呼叫的最下層method傳到主程式

範例如下 :
public class j1123 extends Object {
    public static void main(String args[]) {
        try {
           aaa();
        } catch (Exception e) {
           System.out.println("Exception:"+e.toString());
        }
    } // end of method

    // 由於bbb()會丟出exception,則aaa()必須宣告throws Exception且必須有try{ }段
    // 否則會有編譯錯誤的訊息
    private static void aaa() throws Exception{
        try {
           bbb();
        // 這裡如果不要對Excption訊息加工則不須加catch
        // catch (Exception e) throw e; 是不需要的!
        } finally {
        }
    } // end of method

    private static void bbb() throws Exception{
        // 在程式中利用throw來產生Exception message
       throw new Exception("bbb() exception!");
    } // end of method
} // end of class

2005年11月21日

SOA 參考資訊

1.IBM SOA and Web Services紅皮書
2.IBM SOA and Web Services專欄
3.BEA SOA資源中心

導入服務導向架構 SOA 的策略

導入服務導向架構必須有整體的規劃,確實執行每個步驟,方能克服障礙,確保成功,下列是為一些寶貴的經驗法則,對導入 SOA 有相當大的助益。

1.制定統一的 Data Schema(Canonical Schema):例如原來的 Customer 資料在 ERP 與 CRM 系統有不同的格式,在 SOA 中必須有統一的 Schema。
2.延伸 Legacy System:使用 Web services 把 Legacy System 包裝起來提供開放的服務,是一種不錯的選擇。
3.建立管理服務的機制:包括佈署、監控、量測、Routing 等等。
4.彙集服務 (Orchestrate services):如果彙集一些互動服務可以具有商務意義,則可提供彙集服務給客戶使用,通常對應 User Task 且具有 Business Transaction 特性。
5.使用可靠的訊息傳輸機制:例如使用 Message Queue 比使用 TCP/IP 的 Socket 較穩定。
6.按 Internet/Intranet 的不同,採用適當的身份識別系統與安全機制。
7.採用 Services Interface、Services Facade、Services Implementation 三層架構,提高 Services 的彈性。

From : 如何導入服務導向架構 SOA