FactoryBox 一個Android 代碼生成列子
使用google的auto-service和AbstractProcessor進行代碼生成。看了不少講解AbstractProcessor的教程,後來我一直在需要找其應用的實例。後來在項目中的一個配置文件經常改動想到了自動生成代碼,於是考慮實踐一下
例子
1、需要實現的接口
public interface Event {
void onEvent();
}
2、具體的實現接口的類
@FactoryBox(key = "destroy", product = Event.class)
public class DestroyEvent implements Event {
@Override
public void onEvent() {
}
}
@FactoryBox(key = "resume", product = Event.class)
public class ResumeEvent implements Event {
@Override
public void onEvent() {
}
}
3、自動生成部分
package com.owant.createcode.testcode;
import java.lang.Exception;
import java.lang.String;
public final class EventFactory {
public static Event create(String key) throws Exception {
if("sub_event".equals(key)) {
return new com.owant.createcode.sub.SubEvent();
} else if("create".equals(key)) {
return new com.owant.createcode.CreateEvent();
} else if("destroy".equals(key)) {
return new com.owant.createcode.testcode.DestroyEvent();
} else if("resume".equals(key)) {
return new com.owant.createcode.testcode.ResumeEvent();
} else {
throw new Exception(String.format("沒有到key=%s對應的實現",key));
}
}
}
好處
實現工廠模式的拓展,不關心工廠的實現,工廠由代碼進行生成。減少了更改。
https://github.com/owant/FactoryBox