-----box 程式----- #程式1 import javax.ejb.Remote; @Remote public interface Calculator { public int add(int i, int j); } -----end----- -----box 程式----- #程式2 import javax.ejb.Stateless; @Stateless public class CalculatorBean implements Calculator { public int add(int i, int j) { return i+j; } } -----end----- -----box----- 註1 這部份已超出本文範圍,有疑問的讀者可在Ed Roman的Mastering EJB 3/e (WILEY出版,在theserverside.com可自由下傳pdf檔,台灣有2/e的中譯本)中找到更進一步的資訊。 -----end----- -----box 程式----- #程式3 public class TestCalculatorClient { @EJB private static Calculator adder; public static void main(String[] args) { Properties properties = new Properties(); …(略) InitialContext ic; try { ic = new InitialContext(properties); Object o = ic.lookup(Calculator.class.getName());       adder = (Calculator) PortableRemoteObject.narrow(o,Calculator.class); } catch (NamingException e) { e.printStackTrace(); } int result = converter.add(2, 4); // 測試2+4 = ? System.out.println(result); // 應該要回傳6 } } -----end----- -----box 程式----- #程式4 @Deprecated public String getAddress(String name) {  … } -----end----- -----box 程式----- #程式5 public @interface MyAnnotation{ String myname(); String telephone() default "N/A"; String description() default "N/A"; } J2SE 5.0還提供了一組「Meta-Annotation」用來修飾使用者自訂的Annotation。例如我們可以使用Retention這個Meta-Annotation來標記前面提過的三個Annotation使用時機。Retention標記只含一個RetentionPolicy參數,RetentionPolicy是一個列舉型別(Enum),定義了Annotation的三個使用時機: 1. RetentionPolicy.SOURCE, 2. RetentionPolicy.CLASS,及 3. RetentionPolicy.RUNTIME 假設MyAnnotation想在執行時期由JVM進行額外的處理,則可以在MyAnnotation前加上「@Retention(RetentionPolicy.RUNTIME)」的設定(如程式6)。 -----end----- -----box----- #程式6 @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation{ String myname(); String telephone() default ""; String description() default ""; } -----end----- -----box 程式----- #程式7 Class AnnotationTest{ @MyAnnotation(myname=”try”) public void test() {…} } -----end----- -----box 程式----- #程式8 …(略)… Class annotationTestClass = AnnotationTest.class; Method method = annotationTestClass.getMethod("test"); MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class); // 測試用: 將取得的Annotation屬性值印出來 System.out.println(myAnnotation.myname()); System.out.println(myAnnotation.telephone()); System.out.println(myAnnotation.description()); …(根據這些已經取得的屬性值,做後續的處理)… -----end----- -----box 程式----- #程式9 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Stateless { String name() default ""; String mappedName() default ""; String description() default ""; } -----end----- -----box 程式----- #程式10 public class Ejb3AnnotationHandler implements Ejb3Handler{ …(略) public boolean isEjb(){ if (visible == null) return false; if (EJB3Util.isStateless(visible)) return true; if (EJB3Util.isMessageDriven(visible)) return true; if (EJB3Util.isStatefulSession(visible)) return true; return false; } … public List getContainers(…) { … if (ejbType == EJB_TYPE.STATELESS){ StatelessContainer container = getStatelessContainer(ejbIndex); … } … -----end-----