创建自定义java注释以修改方法

时间:2017-11-28 22:01:13

标签: java android annotations

我想创建一个注释,以便在Spring中使方法像@Async一样异步,但对于Android。我检查了java的注释处理器但它不允许修改现有的类(我们只能创建新的类)我不想使用androidannotation库因为我也想学习如何创建自己的注释

我看到lombok允许修改类(添加getter和setter),我们可以添加自定义注释(https://binkley.blogspot.fr/2014/12/writing-your-own-lombok-annotation.html

但我无法修改此示例以创建asynctask并注入方法的代码。

感谢您的帮助

@AsyncTask
void doSomething(int a){
    Log.d("here");
}

- >

void doSomething(int a){
    new android.os.AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground( Void... voids ) {
            Log.d("here");
            return null;
        }
    }.execute();
}

1 个答案:

答案 0 :(得分:0)

首先,我们定义注释:

cglib

然后我们使用@AsyncTaskimport net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; public class AsyncTaskHandler { @SuppressWarnings("unchecked") public static <T> T handle(T origin) { // collect async methods List<Method> asyncMethods = Arrays.stream(origin.getClass().getMethods()) .filter(m -> m.getAnnotation(AsyncTask.class) != null) .collect(Collectors.toList()); // if no async method, return itself if (asyncMethods.isEmpty()) { return origin; } return (T) Enhancer.create(origin.getClass(), (MethodInterceptor) (obj, method, args, proxy) -> { // if asyn, wrapped in your async code, here I simply create a new thread if (asyncMethods.contains(method)) { // your async logic new Thread(() -> { try { proxy.invoke(origin, args); } catch (Throwable e) { e.printStackTrace(); } }).start(); return null; } return proxy.invoke(origin, args); }); } } 方法创建asyn逻辑:

public class SomeObject {

  public static void main(String[] args) {
    SomeObject so = SomeObject.create();
    so.syncDo("1");
    so.asyncDo("2");
    so.syncDo("3");
    so.asyncDo("4");
  }

  public static SomeObject create() {
    return AsyncTaskHandler.handle(new SomeObject());
  }

  protected SomeObject() {}

  @AsyncTask
  public void asyncDo(String who) {
    System.out.println(who + "\tThread: " + Thread.currentThread());
  }

  public void syncDo(String who) {
    System.out.println(who + "\tThread: " + Thread.currentThread());
  }
}

让我们测试一下我们的代码。

1   Thread: Thread[main,5,main]
3   Thread: Thread[main,5,main]
2   Thread: Thread[Thread-0,5,main]
5   Thread: Thread[Thread-1,5,main]

,输出为:

console.log('parent 1 alleles ' + parent1Alleles);