我正在嘗試學習如何在Java中編寫自定義註釋。爲了學習的目的,我決定嘗試創建一個使用註釋爲類提供可用字段的註釋,例如:注入但不是必需的,作爲單例讓它更簡單(我認爲),但這也是受歡迎的。注入另一個對象的Java自定義註釋
================================= CLASS 1 ========= ========================
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface AutoInject {
}
=================== ============== CLASS 2 ================================ =
// The class to be injected in Main.java
public class TestClass0 {
void printSomething(){
System.out.println("PrintSomething: TestClass0");
}
}
================================= CLASS 3 ===== ============================
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class Main {
TestClass0 ts0;
// Injecting here!!
@AutoInject
public TestClass0 getTso() {
return ts0;
}
public void setTso(TestClass0 ts) {
ts0 = ts;
}
public static void main(String[] args) {
performAnnotationScanOnClass (Main.class);
// Create instance
Main main = new Main();
main.getTso().printSomething();
}
public static void performAnnotationScanOnClass(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof AutoInject) {
AutoInject autoInject = (AutoInject) annotation;
// if (field.get(...) == null)
// field.set(... , value)
}
}
}
}
}
正如你可以在靜態void main()中看到的...我試圖調用TestClass0中的方法,期望它可用。我知道上述內容從接近完成開始就很長,但我剛開始學習註釋並希望得到您的指導。
我們如何能火的一段代碼,即initializez物業無論是在新或當get方法被調用。使用註釋。我想而不改變調用方法。
謝謝!
你認爲你的測試註釋,但你真的重塑CDI。不要...重塑...輪子。 – Perception 2012-02-24 15:52:00
我沒有重新發明任何東西。我正在努力學習其他人如何實現和創造,而不是使用它。你瞭解區別?它的教育目的。 – momomo 2012-02-24 16:24:13
好吧,祝你好運吧!我相信你會學到很多東西。 – Perception 2012-02-24 17:09:02