まず、我々は、アノテーションを定義する -
は
@AsyncTask
void doSomething(int a){
Log.d("here");
}
あなたの助けをありがとう方法:
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]
クラスを変更し、危険であり、すべてのJVMの維持が必要です。生成されたクラスを作成するか、プロキシを使用するのはどうですか? –