gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:53:32 24 4
gpt4 key购买 nike

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

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

但是我无法修改此示例以创建异步任务并注入(inject)该方法的代码。

感谢您的帮助

@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();
}

最佳答案

首先,我们定义注释:

@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface AsyncTask {
}

然后我们使用cglib@AsyncTask方法创建异步逻辑:

import 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);
});
}
}

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

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]

关于java - 创建自定义java注释以修改方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47541636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com