怎麼使用呢?
例子:先利用反射,獲取到註解,而後把利用註解實例化該類的對象
下面有一個例子:(本身寫的哦)
定義一個註解java
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitProvider { /*供應商編號*/ public int id() default -1; /*供應商名稱*/ public String name() default ""; /*供應商地址*/ public String address() default ""; }
對一個類使用註解程序員
@FruitProvider(id = 1728, name = "why", address = "shenzhen") public class Apple { private int appleID; private String appleProvidername; private String appleprovideraddress; public int getAppleID() { return appleID; } public void setAppleID(int appleID) { this.appleID = appleID; } public String getAppleProvidername() { return appleProvidername; } public void setAppleProvidername(String appleProvidername) { this.appleProvidername = appleProvidername; } public String getAppleprovideraddress() { return appleprovideraddress; } public void setAppleprovideraddress(String appleprovideraddress) { this.appleprovideraddress = appleprovideraddress; } }
註解處理器架構
public class FruitInfoUtil { public static Apple getAApple(Class<?> clazz) throws Exception{ FruitProvider fb = clazz.getAnnotation(FruitProvider.class);//經過反射獲取處理註釋 //經過newInstance()生成Apple實例,利用反射的結果進行設置 Apple ap = (Apple)clazz.newInstance(); ap.setAppleID(fb.id()); ap.setAppleProvidername(fb.name()); ap.setAppleprovideraddress(fb.address()); return ap; } }
public class Main { public static void main(String[] args) throws Exception{ Apple a = FruitInfoUtil.getAApple(Apple.class); System.out.println("蘋果商的ID爲:"+a.getAppleID()); System.out.println("蘋果商的名字爲:"+a.getAppleProvidername()); System.out.println("蘋果商的地址爲:"+a.getAppleprovideraddress()); } }
這個實例就很好的說明,如今的框架不少都使用了這種方式來減小配置文件的數量。(由於配置就在代碼裏面了)。app
部分來源:簡書[ALEXIRC]框架