Wednesday, February 27, 2008

แอบดู GWT code

เมื่อวานผมเขียน code GWT ในส่วนที่เกี่ยวกับ java.util.Date
แล้วเกิดสงสัยว่ามัน implement อย่างไร ก็เลยลอง download source code ของ GWT มาดู
เปิดดูแล้วก็ร้อง 'ฮ่อ'

ลองดูบางส่วนที่ผมตัดมาให้ดู

/**
* Represents a date and time.
*/

public class Date implements Cloneable, Comparable<Date>, Serializable {

public Date() {
init();
}

private native void init() /*-{
this.jsdate = new Date();
}-*/
;


public native int getDate() /*-{
return this.jsdate.getDate();
}-*/
;

public native int getDay() /*-{
return this.jsdate.getDay();
}-*/
;

public native int getHours() /*-{
return this.jsdate.getHours();
}-*/
;

public native String toGMTString() /*-{
var d = this.jsdate;
var padTwo = @java.util.Date::padTwo(I);
var month =
@java.util.Date::monthToString(I)(this.jsdate.getUTCMonth());

return d.getUTCDate() + " " +
month + " " +
d.getUTCFullYear() + " " +
padTwo(d.getUTCHours()) + ":" +
padTwo(d.getUTCMinutes()) + ":" +
padTwo(d.getUTCSeconds()) +
" GMT";
}-*/
;

private static String padTwo(int number) {
if (number < 10) {
return "0" + number;
} else {
return String.valueOf(number);
}
}
}

งามดีเหมือนกัน ส่วนที่ cross กันระหว่าง javascript กับ java (ก่อนที่จะแปลงเป็น javascript)

ที่น่าสนใจก็คือ ตอนที่ฝั่ง javascript call มาที่ฝั่ง java
จาก code ข้างบนลองดูวิธีการ call method padTwo

// เริ่มด้วยการอ้างถึง method ที่ต้องการ
// จะเห็นว่ามันใช้ signature ของ method ในการอ้างถึง method ที่ต้องการ
// สิ่งที่ return กลับมาก็น่าจะเป็น javascript function

var padTwo = @java.util.Date::padTwo(I);
...
padTwo(d.getUTCHours()) + ...
...

Related link from Roti